How to center in CSS
Centering anything in CSS seem to be like a mystery game. I usually write CSS and look at the outcome and at some attempts it works.
First of all, you have to ask yourself what do you want to center?
Center text
In case of text, just write text-align: center
Center a block-level element
Centering more than text, a block or an image
You are setting margin-left and margin-right to auto. It has to have a set width, otherwise it would be full width and wouldn’t need centering.
Center a few block-level elements
For centering a few block-level elements you use the famous flexbox and just give the parent element a display: flex and justify-content: center.
If you would like to position multiple block-level elements under each other you can simply use margin auto and a width.
If you happen to know the height of the element
You can center vertically like with position: relative on the parent element and position absolute on the child element with setting a percentage for top:
Center in both directions, vertically and horizontally
Give the parent element display: flex, justify-content: center and align-items: center to center in both directions
There are actually also more ways of centering elements but let’s keep it simple. Now you have no excuse (or at least me) to not center elements in CSS!