Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected size for flex item child

I want to build a column layout with a menu, then a header, then a content container using flexboxes.

I know how to build it in other techs using fixed sizes, calc etc... But have troubles with flexboxes.

Here is a JsFiddle

I have this:

<div class="layout">
  <div class="menu">
    Menu
  </div>
  <div class="header">
    Header
  </div>
  <div class="content">
    <div class="scrollable-content">
      ...
    </div>
  </div>
</div>

.layout {
  overflow: hidden;
  border: solid;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.menu {
  overflow: hidden;
  border: solid red;
  flex-grow: 0;
  flex-shrink: 0;
}

.header {
  overflow: hidden;
  border: solid green;
  flex-grow: 0;
  flex-shrink: 0;
}

.content {
  overflow: hidden;
  border: solid blue;
  flex-grow: 1;
  flex-shrink: 1;
}

.scrollable-content {
  overflow: auto;
  height: 100%;
  width: 100%;
}

As you can see on the JsFiddle, with this code, the .scrollable-content is actually never scrollable, because even while using height: 100% it becomes much larger than his parent div. How can I constrain that div's height to the parent's height?

Note: I know I could put the overflow: auto to the parent .content directly, but for reasons specific to my app I really don't want to: please only submit solutions that do not modify the html structure or change the scrollable container because I already know these solutions. I'm more interested to learn why my approach did not work and how it could be fixed (or not?)

Obviously the content that can be scrolled has a dynamic height and is not a fixed value of 450px like in my JsFiddle.

like image 651
Sebastien Lorber Avatar asked Dec 13 '25 14:12

Sebastien Lorber


2 Answers

You could remove height: 100% from .scrollable-content, and then change the display of .content to flex:

Updated Example

.content {
  overflow: hidden;
  border: solid blue;
  flex-grow: 1;
  flex-shrink: 1;
  display: flex;
}

.scrollable-content {
  overflow: auto;
  width: 100%;
}
like image 50
Josh Crozier Avatar answered Dec 16 '25 00:12

Josh Crozier


You're missing a height: 100% on .content.

Since you're using percentage heights, you need to specify a height for all parent elements of the .scrollable-content.

For a more detailed explanation see: Working with the CSS height property and percentage values

like image 34
Michael Benjamin Avatar answered Dec 16 '25 00:12

Michael Benjamin



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!