Center

There are different ways of centering elements, we will have a look at the most common and easy ones

Horizontally

Horizontally means the same margin from left and right

Vertically

Vertically means the same margin from top to bottom

Block and inline elements

Elements have different behavior depending on their display property.
There are different ways of centering depending on the display property

Horizontally with inline element

Inline elements do not create a new line as the name inline already hints and take only the space of the content. So they can not be centered horizontally, but there is a solution.
You have to put your inline element into a div or other block element and set the property text-align on the block element.

Example

This text is centered horizontally

Code

        .text-horizontally {
            text-align: center;
        }
        

Horizontally with block element

Block elements must have a width and then we can center them with a auto margin. In the case below we will set the second margin value to auto. This means that the browser will have the same margin on the left as ond the right side. In other words the block element is centered!
This only centers the container and not the content.

Example

This is a block element

Code

        .block-center {
            width: 200px;
            margin: 0 auto;
        }

Horizontally with flex box

The flex box allows you to arrange the children in a lot of different ways but also in the center.
Explore the options in the devtools and see instantly how the content will behave.
Keep in mind to set display: flex on the parent and not on the element you want to center.

Example

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat

Code

        .flex-center {
            display: flex;
            justify-content: center;
        }

Vertically with inline element

We can vertically center an element with the vertical-align: middle property. But this only works under some special conditions!

Example

The emoji is centered🚆

Code

        .vertical-align-parent {
            font-size: 1.8rem;
        }
        .vertical-align-parent span {
            font-size: 0.8rem;
            vertical-align: middle;
        }

More information

Vertically with flex box

The simplest way is also here to use the flex box.

Example

This is a block element

Code

        .flex-vertically {
            height: 200px;
            display: flex;
            align-items: center;
        }

More information

Tricks