How to Center in CSS

No Spam.

Wat

Centering in CSS is a pain in the ass. There seems to be a gazillion ways to do it, depending on a variety of factors. This consolidates them and gives you the code you need for each situation.

Select the type of content you want to center in a parent <div> and the size of the parent.

Content

What do you want to center?

Text
Just text, or an inline-level block of text and images.
Div
Any block-level element.

Container

How big is your container <div>?

Width

Known
px
em
%
Unknown
The width is not known until runtime, or needs to be set dynamically.

Height

Known
px
em
%
Unknown
The height is not known until runtime, or needs to be set dynamically.

Alignment

Surprise! This site isn't just for centering. How do you want to align the content?

Horizontally

Left
Center
Right

Vertically

Top
Middle
Bottom

IE Support

What is the minimum version of Internet Explorer you need to support?

None
6
7
8
9
10
11