For centering, which works when?

Trying to center stuff horizontally shouldn’t be so confusing! I find myself cycling through all the possible CSS rules until I find one that works.

I looked around online for a more efficient method and found a helpful discussion on StackOverflow.com that contained several descriptions, illustrations, and resources. I summarized what I learned in the table below.

Stuff to CenterCSS RuleAffect
Block elementmargin: auto;Adjusts left and right margins to center the element.
Text inside elementtext-align: center;Sets horizontal alignment of the inline-level content.
Imagedisplay: block;
margin-left: auto;
margin-right: auto;
Turns image into a block element so its margins can be adjusted.
Content within elementjustify-content: center;Controls alignment of grid columns by adjusting padding within the element.
Does not control items.
Element within parentjustify-items: center;Controls alignment of grid items by adjusting margins within the parent.
Items inside boxjustify-self: center;Overrides justify-items on individual child items. If left on default, inherits values of justify-items.

W3School’s CSS Box Alignments Module Level 3 also contained a helpful graphic that I pasted below. The graphic illustrates how justify-content adjusts padding, justify-items adjusts margins, and justify-self overrides justify-items on individual child elements.

I think I now have a better grasp of which CSS rule to use based on the selector. I look forward to applying what I learned to my next project!

Leave a Reply

Your email address will not be published. Required fields are marked *