CSS: Horizontal Centering
Uncentered Example
This is the scenario: We have a container with an element inside of it that we want to center. I just added a little padding and background colors so both elements are distinquishable.
My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.
Solution 1: Using max-width
& margin
(IE7)
This method is widely used. The upside here is that only the element which one wants to center needs rules.
.quote-1 { max-width: 400px; margin-right: auto; margin-left: auto; }
My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.
Solution 2: Using display: inline-block
and text-align
(IE8)
This method utilizes that inline-block
elements are treated as text and as such they are affected by the text-align
property. This does not rely on a fixed width which is an upside. This is helpful for when you don't know the number of elements in a container for example.
.container-2 { text-align: center; } .quote-2 { display: inline-block; text-align: left; }
My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.
Solution 3: Using display: table
and margin
(IE8)
Very similar to the second solution but only requires to apply rules on the element that is to be centered.
.quote-3 { display: table; margin-right: auto; margin-left: auto; }
My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.
Solution 4: Using translate()
and position
(IE9)
Don't use as a general approach for horizontal centering elements. The downside here is that the centered element will be removed from the document flow. Notice the container shrinking to zero height with only the padding keeping it visible. This is what removing an element from the document flow means.
There are however applications for this technique. For example, it works for vertically centering by using top
or bottom
together with translateY()
.
.container-4 { position: relative; } .quote-4 { position: absolute; left: 50%; transform: translateX(-50%); }
My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.
Solution 5: Using Flexible Box Layout Module (IE10+ with vendor prefix)
.container-5 { display: flex; justify-content: center; }
My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.