How to Center in CSS
5-minute readAssumes standards-compliant rendering, which requires a <!doctype html>
at the top of your document.
Compared to other resources, this page gives you a simple few decisions rather than a giant tree. For most purposes, this selects the best solution, zero redundancy.
The original site also allowed for IE compatibility and generated styles like display: table-cell
or position: absolute
to support ancient versions of the browser. If that’s necessary to you, it’s still archived, but from 2020 onward supporting dumb versions of IE is almost entirely unnecessary. IE11 supports flexbox.
You’ll need to ensure that the width and height of both the content and container are correct for the alignment to have an effect.
A (default) means that one or more properties are redundant.
What is the element displayed as?
How should it be aligned?
Alignment is based on the text directionality, named using LTR. Properties for LTR-only text or cardinal direction are not provided.
A height of 5em
is applied to the container for illustrative purposes.
JavaScript is required for the calculation.
Other methods
There are, of course, other methods to center that may make more sense depending on your situation.
If you’re using a grid layout and want a full-page banner before your content, use some grid properties on the parent
}
and then include your banner element.
}
For some extra flair, I also like width: 100%;
with some kind of background filter to make a kind of centered stripe page before the content.
text-align
isn’t necessary if your centered element’s width fits the content (width: fit-content;
), as the margin property will center it horizontally too.
You can also get away with excluding grid-auto-rows
entirely if your child element is to be dynamically sized, but this can get complicated quickly and the element will forcibly take up minimum height if there are enough other nodes in the grid.
I find this method easier to do than with flexbox, since the root parent decides how tall the first element is, which allows you to minimize redundancies in the DOM. It also has more sane defaults when dealing with more elements in the container; you don’t have to use flex-direction
and the centered element itself defines the centering.
A float: inline-end;
can also come in handy for block-level newspaper-like alignment where you want to throw an image off to the side. This often doesn’t do what you want, but it’s perfect when it does. I can’t use this on my site because margin is defined with flexbox. If this is your situation too, play around with justify-content
.