子元素position:absolute定位之后脫離文檔流,怎么使子元素撐開父元素


純粹的CSS無法實現。因為position:absolute就是脫離文檔流,怎么能讓父元素不塌陷呢? 目前想到的只能用js和jquery來實現了,用js獲取子元素的高度,賦值給父元素。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <title>test</title>
  </head>
  <style>
    .out {
      position:relative;
    }
    .out:after{
        content: "";
        clear: both;
    }
    .inner {
      position:absolute;
      height:60px;
      background-color:#afe;
      width:100%;
    }
  </style>
  <body>
    <h1>父元素的高度崩塌</h1>
    <div class="out">
      <div class="inner">
      </div>
    </div>

    <script>

    window.onload=function(){
        var h = document.getElementsByClassName("inner")[0].offsetHeight;
        console.log(h);
        document.getElementsByClassName("out")[0].style.height = h + 'px';
    
    }
        
    </script>
  </body>
</html>

 

jquery寫法:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM