使 child 的 parent 高度的 x% 由 min-height 设置
Make child having x% of parent's height set by min-height
我的问题不是 this one 的重复问题,因为在我的例子中我使用 min-height
属性,它的工作方式与常见的 [=16] 略有不同=].
我的问题是 this one 的更高级版本,涉及 min-height
属性的违反直觉的 CSS 行为。我想将 child 的身高设置为 parent 由 min-height
属性设置的身高的 80%。如下所示,我们可以通过继承min-height
的值来设置parent的100%的高度,但是对于更小的百分比我不能这样做。当然,我不喜欢明确地为我的 child 设置 100px
。
.parent {
min-height: 100px;
width: 100%;
background-color: green;
}
.child {
width: 30%;
background-color: blue;
}
#c1 {
min-height: inherit; /* =100% of parent's height*/
}
#c2 {
min-height: 80%; /* doesn't work */
}
<div class='parent'>
<div id='c1' class='child'></div>
</div>
<br>
<div class='parent'>
<div id='c2' class='child'></div>
</div>
你必须使用 position: relative
到 parent 和 position: absolute
到 child
.parent {
min-height: 100px;
width: 100%;
background-color: green;
position: relative;
}
.child {
width: 30%;
background-color: blue;
position: absolute;
}
#c1 {
min-height: inherit;
/* =100% of parent's height*/
}
#c2 {
min-height: 80%;
}
<div class='parent'>
<div id='c1' class='child'></div>
</div>
<br>
<div class='parent'>
<div id='c2' class='child'></div>
</div>
我的问题不是 this one 的重复问题,因为在我的例子中我使用 min-height
属性,它的工作方式与常见的 [=16] 略有不同=].
我的问题是 this one 的更高级版本,涉及 min-height
属性的违反直觉的 CSS 行为。我想将 child 的身高设置为 parent 由 min-height
属性设置的身高的 80%。如下所示,我们可以通过继承min-height
的值来设置parent的100%的高度,但是对于更小的百分比我不能这样做。当然,我不喜欢明确地为我的 child 设置 100px
。
.parent {
min-height: 100px;
width: 100%;
background-color: green;
}
.child {
width: 30%;
background-color: blue;
}
#c1 {
min-height: inherit; /* =100% of parent's height*/
}
#c2 {
min-height: 80%; /* doesn't work */
}
<div class='parent'>
<div id='c1' class='child'></div>
</div>
<br>
<div class='parent'>
<div id='c2' class='child'></div>
</div>
你必须使用 position: relative
到 parent 和 position: absolute
到 child
.parent {
min-height: 100px;
width: 100%;
background-color: green;
position: relative;
}
.child {
width: 30%;
background-color: blue;
position: absolute;
}
#c1 {
min-height: inherit;
/* =100% of parent's height*/
}
#c2 {
min-height: 80%;
}
<div class='parent'>
<div id='c1' class='child'></div>
</div>
<br>
<div class='parent'>
<div id='c2' class='child'></div>
</div>