How to set container element’s height so their children will be inside of them with CSS?

Spread the love

Sometimes, we want to set container element’s height so their children will be inside of them with CSS.

In this article, we’ll look at how to set container element’s height so their children will be inside of them with CSS.

How to set container element’s height so their children will be inside of them with CSS?

To set container element’s height so their children will be inside of them with CSS, we use flexbox.

For instance, we write

<section id="foo">
  <header>Foo</header>
  <article>
    <div class="main one"></div>
    <div class="main two"></div>
  </article>
</section>

<div style="clear: both">Clear won't do.</div>

<section id="bar">
  <header>bar</header>
  <article>
    <div class="main one"></div>
    <div></div>
    <div class="main two"></div>
  </article>
</section>

to add some elements.

Then we write

* {
  text-align: center;
}
article {
  height: fit-content;
  display: flex;
  justify-content: space-between;
  background: whitesmoke;
}
article div {
  background: yellow;
  margin: 20px;
  width: 30px;
  height: 30px;
}

.one {
  background: red;
}

.two {
  background: blue;
}

to maker the article element a flex container with display: flex;.

We make its child elements spread around the container with justify-content: space-between;.

The child elements will stay inside the container.

Conclusion

To set container element’s height so their children will be inside of them with CSS, we use flexbox.

Leave a Reply

Your email address will not be published.