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 Center | CSS Rule | Affect |
| Block element | margin: auto; | Adjusts left and right margins to center the element. |
| Text inside element | text-align: center; | Sets horizontal alignment of the inline-level content. |
| Image | display: block; margin-left: auto; margin-right: auto; | Turns image into a block element so its margins can be adjusted. |
| Content within element | justify-content: center; | Controls alignment of grid columns by adjusting padding within the element. Does not control items. |
| Element within parent | justify-items: center; | Controls alignment of grid items by adjusting margins within the parent. |
| Items inside box | justify-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!