Skip Navigation
Madison, Wisconsin
Powderkeg Web Design
December 5, 2014

Our FAVORITE way to center things horizontally in HTML and CSS

Nick
Nick
Our FAVORITE way to center things horizontally in HTML and CSS

Centering things has always been a constant give and take relationship for Developers. There isn’t really a universal way to horizontally center things that is guaranteed to work under any circumstances. Are you trying to center a single element? Are there multiple elements? Do they have varying widths? Does it need to be responsive? Can you add classes to the parent?

One of my favorite ways to tackle horizontal centering is setting the parent css to text-align:center and adding display:inline-block to each of the children. This is especially helpful if you have multiple items of defined or auto width that need to be centered within it’s parent:

three-circles

A really quick and simple way to produce this only requires a couple lines of code.

HTML:

<div class="circles-parent">
   <div class="circle"></div>
   <div class="circle"></div>
   <div class="circle"></div>
</div>

CSS:

.circles-parent { text-align:center; }
.circle         { background:green; border-radius:50%; display:inline-block; margin:0 15px; }

The main styles to point out are the “text-align:center” on the parent and the “display:inline-block” on the circles.

This will center all three circles inside of your parent container. It is basically treating the outside of the inline-block elements as a block level element with auto margins, but it keeps the inline features inside. A further plus is I have found that this works all the way back to IE8 – meaning you can use this tactic pretty much all the time.

There are plenty of other ways to center things, and each of them have their uses. I happen to find this way the quickest and easiest way to accomplish the task.

 

Nick Kalscheur

Nick Kalscheur

Lead Developer