How to center a div block without the width with CSS?

Spread the love

Sometimes, we want to center a div block without the width with CSS.

In this article, we’ll look at how to center a div block without the width with CSS.

How to center a div block without the width with CSS?

To center a div block without the width with CSS, we use flexbox.

For instance, we write

<div class="container">
  <div class="centered">This content is centered</div>
</div>

to add a nested div.

Then we write

.container {
  display: flex;
  flex-direction: column;
}
.centered {
  margin: 0 auto;
}

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

And then we make the inner div centered with margin: 0 auto;.

Conclusion

To center a div block without the width with CSS, we use flexbox.

Leave a Reply

Your email address will not be published.