纯粹的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; 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写法: