Centering

How to center anything with CSS

Already I'm gritting my teeth because of my British English wanting to 'centre' everything instead, but there you go.

This is how it works:

Inline Elements

Block Elements

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;

Three

little

elements

place-content: center;

See

how they

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;

Three

little

elements

place-items: center;

See

how they

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.

Three

little

elements

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;

Two

elements

place-items: center;

See how

they center

justify-content: center;

Two

elements

place-content: center;

See how

they 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!

Two

elements

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

Three

little

elements

flex column

Two

elements