Centering in CSS for Beginners

One of the things that frustrate my students when they first start learning CSS is how to center elements. There are many techniques, many of them not very intuitive. Some require that you apply CSS to the element itself, while others to the parent. It’s very frustrating.

This tutorial is meant for beginners who struggle to find the right approach to centering things. It’s not a comprehensive list of techniques, but a short list meant to help the confused.

Centering Text and Images with text-align: center

Although images are not text, they can be aligned with this rule. For this technique to work, you need to place it on the parent of the text or image.

See the Pen Centering Text and Images by Alicia Ramirez (@coopersita) on CodePen.36477

Centering Images and Blocks with margin: 0 auto

Any block element (<p>, <div>, <header>, <main>, etc.) that is smaller than its parent (not 100% wide) can be centered by setting the horizontal margin to auto (dividing any leftover space equally on both sides). This CSS is applied directly to the element.

See the Pen Centering Containers by Alicia Ramirez (@coopersita) on CodePen.36477

 

Any non-block element can be aligned this way as well (including images, which are inline, that’s why text-align: center works on them). They just need to be converted into a block element with display: block.

See the Pen Centering Images as Blocks by Alicia Ramirez (@coopersita) on CodePen.36477

Centering Horizontally and/or Vertically with Flexbox

Flexbox is a very powerfull tool, which can be used to center its children. The display: flex rule needs to be applied to the parent. If you want to align vertically, the parent needs to be taller than the children. Here’s an example:

See the Pen Centering Inside a Container Using Flexbox by Alicia Ramirez (@coopersita) on CodePen.36477

 

For theses and more examples, go to my centering collection on CodePen. There you’ll find how to center using CSS grid, and how to do hero type sections using flexbox.

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">