下面代码子元素高度是0
<div class="container">
<div class="child"></div>
</div>
<style>
.container {
min-height: 100px;
border: 1px solid;
}
.child {
height: 50%;
background: red;
}
</style>
-
第一种: 父元素设置position: relative, 子元素设置 position:absolute
<div class="container">
<div class="child"></div>
</div>
<style>
.container {
min-height: 100px;
border: 1px solid;
position: relative;
}
.child {
width: 100%;
height: 50%;
background: red;
position: absolute;
}
</style>
-
第二种: 给父元素加一层 box, 给 box 添加 flex 布局
<div class="box">
<div class="container">
<div class="child"></div>
</div>
</div>
<style>
.box {
display: flex;
}
.container {
width: 100%;
min-height: 100px;
border: 1px solid;
}
.child {
height: 50%;
background: red;
}
</style>
-
父元素添加 display: grid
<div class="container">
<div class="child"></div>
</div>
<style>
.container {
width: 100%;
display: grid;
min-height: 100px;
border: 1px solid;
}
.child {
height: 50%;
background: red;
}
</style>
-
第四种:给子元素添加 min-height inherit,规定从父元素继承 min-height 属性的值。
<div class="container">
<div class="child"></div>
</div>
<style>
.container {
min-height: 100px;
border: 1px solid;
}
.child {
height: 50%;
background: red;
min-height: inherit;
}
</style>
-
父元素添加 display: flex; flex-direction: column; 子元素添加 flex: auto
<div class="container">
<div class="child"></div>
</div>
<style>
.container {
min-height: 100px;
border: 1px solid;
display: flex;
flex-direction: column
}
.child {
height: 50%;
background: red;
flex: auto;
}
</style>
- 第六种: display:table;
<div class="container">
<div class="child"></div>
</div>
<style>
.container {
min-height: 100px;
border: 1px solid;
display: table;
}
.child {
height: 50%;
background: red;
}
</style>