在 CSS 中,可以使用 height: 100%
或 height: inherit 将元素 X 的
。这仅在 X 的父级指定了高度时才有效。height
属性设置为与 X 的父元素相同的高度
有没有办法让元素从其具有指定高度的最近的祖先继承高度?
所以在这样的情况下:
index.html
<div class="A">
<div class="B">
<div class="C">
Content
</div>
</div>
</div>
index.css
.A {
height: 200px;
}
.C {
height: 100%;
}
C
将从 A
获取其高度 (200px),即使 B
在层次结构中位于它们之间。你可以想象这样一种情况,其中的嵌套比本例中的要多得多,在其中为每个中间元素添加 height: 100%
是一件很麻烦的事情。
最佳答案
使用 CSS 选择器。创建一个 div 包装器(或将 .A 作为您的包装器 div)并执行 .wrapper div {height: 100%;}
。这会将样式应用于您在包装器 div 下指定的任何元素。
来源:css all divs vs direct child divs
.A {
height: 60px;
border:solid 1px black;
}
.B {
height:inherit;
background-color: blue;
}
.C {
height: 100%;
border:solid 1px blue;
}
.D {
height: 30px;
background-color: green;
border: 1px solid white;
}
.E {
padding: 10px;
}
.wrapper div {
height: 100%;
background-color: red;
border: 0px;
}
<div class="wrapper">
<div class="A">
<div class="B">
<div class="C">
<div class="D">
<div class="E">
Content
</div>
</div>
</div>
</div>
</div>
</div>
关于html - CSS高度继承,跳代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649289/