How to make a div’s height expand with its content with CSS?

Spread the love

Sometimes, we want to make a div’s height expand with its content with CSS.

In this article, we’ll look at how to make a div’s height expand with its content with CSS.

How to make a div’s height expand with its content with CSS?

To make a div’s height expand with its content with CSS, we use flexbox.

For instance, we write

<div class="flex-container">
  <header>
    <h1>Header</h1>
  </header>

  <section class="content">Content</section>

  <footer>
    <h4>Footer</h4>
  </footer>
</div>

to add some nested elements.

Then we write

body {
  margin: 0;
}

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

header {
  background-color: #3f51b5;
  color: #fff;
}

section.content {
  flex: 1;
}

footer {
  background-color: #ffc107;
  color: #333;
}

to make the outer div a flex container with display: flex;.

We set its flex direction to column with flex-direction: column;.

And we make the section element with class content will the remaining height of the container with

section.content {
  flex: 1;
}

Conclusion

To make a div’s height expand with its content with CSS, we use flexbox.

Leave a Reply

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