How do I center an element horizontally and/or vertically with TailwindCSS?

Asked about 1 month ago Viewed 9 times

How can I center an element horizontally and/or vertically in TailwindCSS? Is there more than one way to accomplish this, and if so, what are the pros and cons of each method and in what cases should they be used?

<div class="">
    <span>Center Me</span>
</div>
1
w
79
1 Answer
Sort by
Posted about 1 month ago

Recommended and Modern Options

Flexbox - Most Common and Versatile

flex combined with justify-center (horizontal centering) and items-center (vertical centering) will center items within the container.

<div class="flex justify-center items-center size-96">
    <span>Center Me</span>
</div>

This is the most modern and probably the most used (by far) option, especially since the flexbox layout is so common in modern web development. It's flexible for dynamic content, responsive layouts, and it's easy to center multiple children at a time. Probably the only con is that the parent container must be a flexbox.

Grid Layout

grid combined with place-items-center provides another option that is especially useful if you were already planning to work with a grid layout.

<div class="grid place-items-center size-96">
    <span>Center Me</span>
</div>

If all you want to achieve is the centering of multiple elements and you don't need to make use of grid layout features, I would probably recommend using the flexbox option listed above instead.

More Niche/Use-Case Specific Options

Absolute Positioning with Transforms

Uses a positioning context (relative parent) and absolute positioning with with translate transforms. This is one of the more complex options but can be very useful depending on what you're trying to accomplish.

<div class="relative size-96">
    <span class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
         Center Me
    </span>
</div>

This works even if the parent element isn't a flexbox or grid container, but requires a positioning context (relative parent or otherwise). I would recommend this only for popups, modals, elements overlapping others, or other use-cases that make the other options not viable. Absolute positioning and transforms tend to make responsive design and other common features far more difficult to implement.

Margin Auto (Horizontal Only)

mx-auto automatically adds equal horizontal (left and right) margins to center block elements, it does not works for inline OR inline-block elements and requires a defined width.

<div class="size-96">
    <div class="mx-auto w-fit">Center Me</div>
</div>

auto margin is probably the least reliable method of centering with possibly the most gotchas. I would heavily prefer other method but in some cases mx-auto can be very useful, it's at your discretion to decide when the right time to use it is.

1

Your Answer

You Must Log In or Sign Up to Answer Questions