How to align a float: left div to center with CSS?

Spread the love

To align a float: left div to center with CSS. we use flexbox.

For instance, we write

<div id="container">
  <div class="block">1</div>
  <div class="block">2</div>
  <div class="block">3</div>
  <div class="block">4</div>
  <div class="block">5</div>
</div>

to add nested divs.

Then we write

#container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.block {
  width: 150px;
  height: 150px;
  background-color: #cccccc;
  margin: 10px;
}

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

We make overflowing elements wrap to the next row with flex-wrap: wrap;.

And we center align the inner divs horizontally with justify-content: center;.

Leave a Reply

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