html - CSS高度继承,跳代

标签 html css inheritance height

在 CSS 中,可以使用 height: 100%height: inherit 将元素 X 的 height 属性设置为与 X 的父元素相同的高度。这仅在 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/

相关文章:

html - 单击单选按钮时如何突出显示标签?

java - 我们如何实现单选按钮而不是下拉菜单?

html - 让包含不同字体大小的文本的多个 div 都对齐到底部的方法?

html - 用 CSS 替换内容 - 可访问性影响?

html - sub div css 格式化问题?

java - 使用泛型将子类构建器初始化为父构建器的类型

c++ - 接口(interface)、继承以及它们之间的关系

css - 这个符号在做什么? CSS 内容 : "\e850";

javascript - 在传播期间修改事件属性

Javascript Proxy set() 继承对象的局部属性