How to horizontally center an element with CSS?

Spread the love

Sometimes, we want to horizontally center an element with CSS.

In this article, we’ll look at how to horizontally center an element with CSS.

How to horizontally center an element with CSS?

To horizontally center an element with CSS, we can use flexbox.

For instance, we write

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

to add a div within a div.

Then we write

#inner {
  border: 1px solid black;
}

#outer {
  border: 1px solid red;
  width: 100%;
  display: flex;
  justify-content: center;
}

to add display: flex and justify-content: center; to horizontally center the contents inside.

Conclusion

To horizontally center an element with CSS, we can use flexbox.

Leave a Reply

Your email address will not be published.