How to horizontally center an element without Flex

jetthoughts-dev

JetThoughts Dev

Posted on June 1, 2022

How to horizontally center an element without Flex

Centered elements with Flex it is very easy to style, what about not use Flex?

<div class="wrapper">
  <div class="inner">Centered</div>
</div>
Enter fullscreen mode Exit fullscreen mode

Table

It will make the inner element center horizontally and it works without setting a specific width.

.wrapper {
  display: table;
  margin: 0 auto;
}
Enter fullscreen mode Exit fullscreen mode

Fixed width

Need to apply this CSS to the inner. You should set any width less than the containing wrapper will work. The margin: 0 auto is what does the actual centering.

.inner {
  max-width: 25%;
  margin: 0 auto;
}
Enter fullscreen mode Exit fullscreen mode

Display: Inline-Block

display: inline-block makes the inner element into an inline element that can be centered with text-align: center

.wrapper {
  text-align: center;
}

.inner {
  display: inline-block;
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
jetthoughts-dev
JetThoughts Dev

Posted on June 1, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related