Search code examples
htmlcss

How to make my container fill the bottom of my page (if the page is not scrollable)


I am facing this issue, i think the answer is very simple but I can't figure it out.

First I'll explain with words : I have a dark background, my nav is transparent (so it looks like the background) and my page container is a kind of big white card.

  • when the page is scrollable => the page container height hits the bottom of the page : scrollable view
  • when the page is not scrollable (not enough content to make it scrollable) => there is a empty area till the bottom : not scrollable view

I checked CSS and there is no strange behavior. I tried some stuff found on the web, but it did the opposite. here is my dom structure :

#root, html {
  background: #353333;
}
.page-container {
  background-color: white;
  margin: 0 1rem;
}
.grid {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows: auto;
  column-gap: 1.5rem;
  row-gap: 1rem;
  height: fit-content;
}
<html>
  <body>
    <div id="root">
      <div class="layout">
        <div class="navigation">logo, nav links ...</div>
        <div class="page-container">
          <div class="grid">
            <div>div</div>
            <div>div</div>
            <div>div</div>
            <div>div</div>
            <div>div</div>
            <div>div</div>
            <div>div</div>
            <div>div</div>
            <div>div</div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

I can't really share due to privacy policies.. If I am missing something, just ask and I will update my post

I tried to increase body & root height


Solution

  • Rationale

    When you run into a problem like this, it's usually wise to narrow it down to the minimal elements required, so that you can clearly see which CSS-properties are needed and which aren't.

    Steps

    In your example you need to do three things:

    1. Make sure the parent containers are displayed at 100% height

    2. Set display: flex on the parent node, in this case .layout

    3. Set flex-grow: 1 on the nodes that need to grow

    Working example

    html, body {
      height: 100%;
      margin: 0;
      background: #353333;
      color: #ccc;
    }
    
    .layout {
      height: 100%;
      display: flex;
      flex-direction: column;
    }
    
    .growing-child {
      flex-grow: 1;
      background-color: white;
      color: #333;
    }
      
    <div class="layout">
      <header>This container does not grow</header>
    
      <main class="growing-child">
        <h1>Content</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
      </main>
    
      <footer>Optional footer</footer>
    </div>

    Note

    If you have html and body and #root and layout, then all of them need to either be of 100% height or otherwise grow along with the content.