Home > Enterprise >  Setting flex-grow: 1 causes div height to go beyond available space
Setting flex-grow: 1 causes div height to go beyond available space

Time:09-23

I have some html like this:

.container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px;
  background-color: aqua;
}

.box {
  width: 100%;
  height: 100%;
  flex-grow: 1;
  background-color: cadetblue;
  display: flex;
  flex-direction: column;
}

.fill {
  flex-grow: 1;
  background-color: antiquewhite;
}

.middle {
  height: fit-content;
  background-color: azure;
  justify-self: flex-end;
}

.bottom {
  height: fit-content;
  background-color: darkgray;
  justify-self: flex-end;
}
<div >
  <h3>Title</h3>

  <div>Some Stuff</div>

  <div >
    <div >Fill</div>

    <div >Middle</div>

    <div >Bottom</div>
  </div>
</div>

I want the divs middle and bottom to stack at the bottom of the screen, and for the div fill to, as the name suggests, fill the remaining space without pushing the middle/bottom divs off the screen or creating a scrollbar, however it doesn't display like that:

example screenshot from stackblitz

Note that the middle and bottom divs are not visible and the scrollbar created by the fill div expanding beyond the available height.

See this StackBlitz for a demo: https://stackblitz.com/edit/angular-ivy-mwtwdg?file=src/app/hello.component.scss

CodePudding user response:

I had to update a lot of CSS but feel free to take a look.

The right approach to any angular project is to have clean from the very first component (app component), and cascade it down to any other component.

Demo stackblitz

EDIT : comment explanation

"The right approach" can be explained quickly like this :

  • html and body should be at 100% of the page
  • App component should be at 100% and in display block
  • Any component that requires some specific layout (flex, grid), should be constrained by its parent or an absolute size, and display block.

The issue with Angular is that when you create a component, it is not set to display: block. This means the component is kind of free in the DOM flow, and this results in the kind of issues you have encountered.

When you set display: block to EVERY component (you can use angular.json to make it automatic), then you have a more deterministic approach to the CSS, where what you expect is what you get.

In your case, since the components were not display:block, they could not be constrained by height, width, or their parents.

Added to that, the fact that you wrote some probelmatic CSS (for instance, the sidenav-container being 100% of the height of its parent : what about the toolbar ?), this resulted in your issue.

As a final word, when it comes to CSS in Angular, be sure to have clean CSS from the top, and when you have any issue like you did, crawl back component by component, to find and correct the unclean ones !

  • Related