純粹的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寫法: