How can I horizontally center an element?
When you need to horizontally center a child element, apply display: flex;
and justify-content: center;
to the parent:
If the child has a known width, you can center it using margin: 0 auto;
:
These methods readily dispatch elements to the center stage with just a few CSS snippets.
Flexbox in action
Flexbox is a handy layout model that gives you excellent control over the alignment and distribution of items in a container. Not just for horizontal centering, it's equally proficient to manage vertical centering:
Fallback for older browsers
Regrettably, not every antiquated browser supported flexbox. If your audience uses IE8 or IE9, you'll need a workaround using display: table
and display: table-cell
:
Dodge with absolute positioning and transforms
Combining position: absolute
with CSS transforms provides an effective shifty solution for centering:
No-Width-Limits club
For centering fanatics who don't care about setting predefined widths, here's a preferred method:
When specifics matter
For fixed-width elements, you can leverage the below styles:
For variable width elements, the transform property can offset the position:
For complex layouts combining different methods may become necessary:
Was this article helpful?