【问题标题】:CSS height inheritance, skipping generationsCSS高度继承,跳过世代
【发布时间】:2016-06-06 13:46:38
【问题描述】:

在 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 获得高度(200 像素),即使B 在层次结构中位于它们之间。您可以想象这样一种情况,其中嵌套比本示例中的要多得多,在每个中间元素中添加 height: 100% 会很麻烦。

【问题讨论】:

  • 有什么理由不能只在 .C 上设置固定高度,从而扩展 .A 吗?大多数时候我遇到这个问题是因为我的 HTML 结构很差(不必要的包装器等)。我很好奇你的具体情况

标签: html css inheritance height


【解决方案1】:

使用 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>

【讨论】:

  • 原提问者有机会查看这些答案吗?
【解决方案2】:

div C 从 B 获取高度,B 从 A 获取高度。如果 B 是继承的。 将此添加到 B 类:

height:inherit; 

我用颜色标记 div,评论它看看我做了什么。

https://jsfiddle.net/0saut255/1/

【讨论】:

  • 我在我的问题中注意到了这个解决方案。我的观点是,如果嵌套更多,因此 A 和 C 之间的层数更多,那么必须将height: inherit 单独放在所有这些层上会很糟糕。所以我要求一种方法来“跳过”所有介于height: inherit 之间的方法,而只是从最近的祖先那里继承。
【解决方案3】:

您可以创建一个主类来保存 100% 高度规则,然后将其添加到链中的所有 div 中。这只会将问题转移到 HTML 而不是 CSS,但它会将 100% 的高度传递给所有孩子

.A {
height: 200px;
}
.fullHeight {
height: 100%;
}

然后在你的 HTML 中

<div class="A">
  <div class="B fullHeight">
    <div class="C fullHeight">
        Content
    </div>
  </div>
</div>

底线是,无论您选择哪种方法,您都必须使用一些指示符标记每一层,它应该查看上面的元素的高度。

【讨论】:

  • 好吧,一个好主意(我考虑过,但仍然试图避免在每一层单独做一些事情)。
【解决方案4】:

你可以添加 .A div{ height: 100%; } 在您的 CSS 上,然后如果需要调整 B 的高度,请使用 !important。例如:.B{ 高度:150px !important; }

.A{ height: 300px; }
.A div{ height: 100%; }
.B{ width: 500px; height: 200px !important; }
.C{ width: 100px; }
<div class="A">
    <div class="B">
        <div class="C">
            Content
        </div>
    </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多