DEV Community

EXtreme Stack
EXtreme Stack

Posted on

CSS height property

Sorry this is a dumb question but why does the height property not apply to an element when you make use of percentage relative units. Example, if you have a div element and apply a CSS rule div{width:25%;height:25%;}, the width declaration applies to the div element but the height doesn't.

Top comments (2)

Collapse
 
matthri profile image
Matthias

Hi, this is because the height of a div element depends on the height of the containing block of the div element (see MDN Web Docs).
Therefore if the containing, let's call it parent element has a hight explicit height of 400px the inner element will have a height of 100px if you apply your CSS rule.
If the parent element has no explicit height the height of the inner element is set automatically by the browser (height: auto;).
An exception is when the element to which you apply your CSS rule is positioned absolute (position: absolute;), if thats the case the height of the element depends on the height of the next explicit positioned element or the viewport and in your case it has a height of 25% of the element.

Let me give you a little example:

<div class="outer">
    <div class="inner">
        Test
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

in the first case our CSS classes will look like this

.inner {
    height: 25%;
}
.outer {
}
Enter fullscreen mode Exit fullscreen mode

now the inner div will have the height of the contained Text.
In the second case our CSS classes are the following

.inner {
    height: 25%;
}
.outer {
    height: 1000px;
}
Enter fullscreen mode Exit fullscreen mode

in this case the inner div will have a height of 250px because the outer div has an explicit height.

The last one is our edge case with the following classes

.inner {
    position: absolute;
    height: 25%;
}
.outer {
}
Enter fullscreen mode Exit fullscreen mode

Now our inner element is positioned absolute and in this case it will become 25% of the height of the viewport. Be careful with this approach since the position: absolute; will affect the positioning and the flow of the element on your site.

I hope I could help you with this, feel free to ask if you have any further questions.

Collapse
 
onyebuchidaniel60 profile image
EXtreme Stack

Thank you very much Matthias. I understand clearly now