Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying height of divs as 100% of container minus height of sibling div

Tags:

html

css

I've got a divs in the following layout

<html style="height:100%">
<body style="height:100%">
    <div id="divBody" style="height:100%;width:1000px">
        <div id="divHeader" style="height:30px"></div>
        <div id="divContent" style="height:100%">
            <div id="divLeft" style="height:100%; float:left; width:200px; border-left:1px solid black"></div>
            <div id="divRight" style="width:800px"></div>
        </div>
    <div>
</body>
</html>

My problem is that divContent how has a height of 100% of the body. What I need it to do is take up the entire height of divBody minus the height of divHeader. So I set the height of divContent to auto:

<html style="height:100%">
<body style="height:100%">
    <div id="divBody" style="height:100%;width:1000px">
        <div id="divHeader" style="height:30px"></div>
        <div id="divContent" style="height:auto">
            <div id="divLeft" style="height:100%; float:left; width:200px; border-left:1px solid black"></div>
            <div id="divRight" style="width:800px"></div>
        </div>
    <div>
</body>
</html>

Now divContent's height is correct, it is 100% of divBody minus the height of divHeader, but now the height of divLeft does not fill 100% of it's parent (divContent). How can I get the best of both worlds here?

like image 591
Jeremy Avatar asked Oct 29 '25 05:10

Jeremy


2 Answers

Since you know the height of #divHeader is 30px, the simple answer to your question would be to use calc() on #divContent like this:

#divContent {
  height: calc(100% - 30px);
}

The tough part is to set height of a sibling like #divContent when the height of the other sibling(s) are unknown or dynamic. That's when CSS Flex comes in handy:

.flex {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.top {
  flex-shrink: 0;
}

.bottom {
  height: 100%;
}

Element with class bottom will use 100% height minus the height of its siblings. The flex-shrink: 0 rule is important, primarily for iOS devices, to avoid shrinking on the sibling.

Working example on Codepen here.

like image 104
Calsal Avatar answered Oct 31 '25 18:10

Calsal


You should go on with the percentages instead of using fix amount of pixels for the header. The widht of header and content should be 100%, but the height "auto", so it actually adjusts to their real need within the body div you're using.

Regarding to div left and right, both should set to height 100% I guess

like image 42
Sebas Avatar answered Oct 31 '25 18:10

Sebas