html – How to set CSS height: 100% correctly for 1 sibling and fluid height for the other sibling?-ThrowExceptions

Exception or error:

I have a container that occupies 50% of the height of my page. That works OK.
Now I need to have inside that container 2 children: one that I don’t know the height (fluid according to content) and another that should occupy the remaining height space of the container.

I know there is a weird thing about this CSS as when you have 2 siblings and you set one of the to height 100% it doesn’t take into account the other sibling height but instead just uses 100% of their parent block level element. That is fine: I can find out a solution if I set my first child with a fixed height.

My problem now is that my first child needs to be a fluid height. How can I do this using CSS? (I know how to fix it using JS to get .outerHeight).

Pastebin – Fixed height for #1 child example

How to solve:

Try like this: DEMO

HTML:

<div id="container">
    <div id="c1">
        <p>a</p>
        <p>bbb</p>
    </div>
    <div id="c2">ghgh</div>

CSS:

#container {
    position: fixed;
    top: 0;
    left: 0;
    width: 400px;
    height: 50%;
    padding: 0;
    margin: 0;
    border: 1px solid red;
    display:table;
}
#c1 {
    height: 90px;
    background-color: #999;
}
#c2 {
    /*height: calc(100% - 90px);*/
    background-color: #f0f0f0;
    min-height:100%;
}
#c1, #c2 {
    display:table-row;
}

###

In your Pastebin I see that you have used calc(). It works great when you know the height of the sibling. But when the height of the other sibling(s) is unknown or dynamic I would use CSS Flexbox instead:

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

.top {
  flex-shrink: 0;
}

.bottom {
  height: 100%; // 100% height of its container minus height of siblings
}

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 other siblings. It should serve your needs for fluid height.

Working example on Codepen here.

Leave a Reply

Your email address will not be published. Required fields are marked *