Alex Zhukovskiy Alex Zhukovskiy - 3 days ago 7
CSS Question

Shrink second child to always fit a parent

Assume we have following markup

<div id="parent">
<div id="header">
</div>
<div id="content">
</div>
</div>


header
div is variable-sized, so we don't know what exact offset gets the second one. We want to accomplish two following objectives:


  1. The second div should never overflow its parent. If overflow occurs, the scrollbar appears.

  2. It should be done in pure-CSS manner, for IE9+ if possible.



I have been thinking that this task is pretty easy, really, I just want my div to be non-overflowing, that's all, but I found that it's not possible even with flexbox.

When i say
overflow
I mean vertical overflow, because they all are of the same width.

Answer

It's very simple to do this with Flexbox, just set flex-direction: column on parent and overflow-y: auto on content.

#parent {
  height: 300px;
  border: 1px solid black;
  display: flex;
  flex-direction: column;
  width: 200px;
}
#header {
  background: lightblue;
}
#content {
  flex: 1;
  overflow-y: auto;
  background: lightgreen;
}
<div id="parent">
   <div id="header"><br><br><br></div>
   <div id="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque culpa consequuntur repellat ex, ut cumque fugit minus, itaque omnis, cum quidem in debitis. Consequuntur perspiciatis corporis nostrum similique eveniet voluptates cumque molestias rerum, distinctio accusamus? Quas explicabo, ea praesentium ad velit rem accusamus officia quibusdam ut accusantium possimus dignissimos dolores ipsum quia placeat tenetur omnis veritatis molestias voluptatibus consequuntur odit consectetur vero, voluptas corporis laudantium! Rem laborum excepturi quia temporibus, veniam blanditiis tempore eaque nostrum suscipit, quam laboriosam ratione provident obcaecati iste magni molestiae explicabo quibusdam expedita veritatis officia, debitis officiis sed. Neque veniam eius saepe. Quo doloremque, repellat mollitia!</div>
</div>

Comments