Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS height inheritance, skipping generations

In CSS, the height property of an element X can be set to the same height as X's parent using either height: 100% or height: inherit. That only works if X's parent has its height specified.

Is there a way to make an element inherit height from its nearest ancestor that has a specified height?

So that in a situation like this:

index.html

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

index.css

.A {
    height: 200px;
}

.C {
    height: 100%;
}

C would get its height (200px) from A, even though B is in between them in the hierarchy. And you can imagine a situation in which there is much more nesting than in this example, where it's a hassle to add height: 100% to every intermediate element.

like image 342
tscizzle Avatar asked Oct 28 '25 09:10

tscizzle


1 Answers

Utilize a CSS selector. Create a div wrapper (or make .A your wrapper div) and do .wrapper div {height: 100%;}. This applies styles to any element you specify under your wrapper div.

Source: 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>
like image 156
TimesWasting Avatar answered Oct 31 '25 01:10

TimesWasting



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!