JT Book a call

Blog

How to horizontally center an element without Flex

Published

2 min read

How to horizontally center an element without Flex
In this post

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

<div class="wrapper">
  <div class="inner">Centered</div>
</div>

Table #

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

.wrapper {
  display: table;
  margin: 0 auto;
}

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;
}

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;
}

Why margin: auto centers #

A block element fills the full width of its parent by default, so there is no free space to share. Once you make it narrower, the browser has space left over, and auto margins on the left and right split it equally (MDN: margin). That is why the first two tricks work: display: table makes the box only as wide as its content, and max-width caps it.

The same trick without guessing a width #

If you don’t want to pick a width, let the content decide it:

.inner {
  width: fit-content;
  margin: 0 auto;
}

Chrome measures the “Centered” label inside a 600px wrapper at 66px wide, leaving 267px of space on each side. width: fit-content works without a prefix in Chrome 46+, Firefox 94+ and Safari 11+ (MDN compatibility data).

text-align is inherited by the content #

With the inline-block approach, text-align: center on the wrapper also reaches every line of text inside .inner, because text-align is inherited. For a paragraph that is rarely what you want, so reset it:

.inner {
  display: inline-block;
  text-align: left;
}

Choosing the right horizontal trick #

  • The box has a known or maximum width: max-width with margin: 0 auto.
  • The width should follow the content: width: fit-content with margin: 0 auto.
  • You are centering a few inline things, such as buttons in a row: text-align: center on the parent and inline-block on the children.

Read next

Tell us what you need built

JetThoughts has been building software since 2008. Book a call, or write to sales@jetthoughts.com. You'll leave the call with a written one-page scope within 2 working days.

#01 Paul Keen
Paul KeenFounder & Open Source Contributor

A 30-minute call; pick a time.