Flex and Grid
Some real talk first - flex and grid are a lot when you first encounter them!
To get acquainted with these layout-building CSS tools, I recommend these two CSS-Tricks guides:
That said, the tl;dr is that you want to use the following CSS on an element with
OR display: grid;
You can thank me later, or read on to find out more:
Rows - Horizontal centering
Below is a simple flex container (which defaults to rows, not columns), declared with just
display: flex; and
There are two properties you can use to get stuff to center horizontally in the default horizontal flex box:
Rows - Vertical centering
When your flexbox is taller, you may want to center vertically. Then you can use the sisters to justify- and place-content,
The two properties
align-items are complementary, you can use them together to centre both horizontally and vertically. It's also hard to remember which one is which - what if it's justify-items and align-content? Argh!
This is why the
place-items properties are handy, as you need not remember which goes with which.
Columns - The properties flip
Now let's look at a flex box flow that has been turned 90 degrees, with
Now the two propeties swap,
align-items/place-items now does the horizontal centering, while in a taller box than the contents,
justify-content/place-content are needed to keep the elements inside a flex box vertically centered.
You can probably see now that sticking to
place-items and setting them both to
center can save you some time, unless you have a fantastic memory!
Child property align-self
There's one special case, if you want to center just one of your flex elements, you can use