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 class="container"
:
.container {
display: flex;
OR display: grid;
place-content: center;
place-items: center;
}
You can thank me later, or read on to find out more:
Flex
Rows - Horizontal centering
Below is a simple flex container (which defaults to rows, not columns), declared with just display: flex;
and gap: 1rem;
.
There are two properties you can use to get stuff to center horizontally in the default horizontal flex box:
justify-content: center;
place-content: center;
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, align-items
and place-items
align-items: center;
place-items: center;
The two properties justify-content
and 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-content
and 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 flex-direction:column;
.
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.
align-items: center;
place-items: center;
justify-content: center;
place-content: center;
You can probably see now that sticking to place-content
and 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 align-self: center;
flex row
flex column