<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
.father {
margin: 100px;
width: 300px;
background-color: red;
position: relative;
}
.son1 {
width: 100px;
height: 200px;
background-color: pink;
}
.son2 {
width: 100px;
height: 100%;
background-color: yellow;
position: absolute;
}
</style>
</head>
<body>
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
</div>
</body>
</html>
父元素高度自适应,父元素高度由son1撑开,高度为200px。
son2的高度是100%,如果不加“绝对定位”,那么height100%是无效的,加了之后是有效的。
有大佬帮忙解下疑惑吗(为什么子元素加了position:absolute,子元素height100%就生效),谢谢!
加了绝对定位后,元素脱离文档流,父元素的高度会完全由son1撑起,这时候son1和父元素高度是可以确定的,再来计算son2的高度是可以计算的。而不脱离文档流,父元素由son1和son2撑起,son2高度和父元素都需要相互计算,算不出来