Elements have different behavior depending on their display property.
There
are different ways of centering depending on the display property
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.
.text-horizontally {
text-align: center;
}
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.
.block-center {
width: 200px;
margin: 0 auto;
}
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.
.flex-center {
display: flex;
justify-content: center;
}
We can vertically center an element with the vertical-align: middle property.
But this only works under some special conditions!
The emoji is centered🚆
.vertical-align-parent {
font-size: 1.8rem;
}
.vertical-align-parent span {
font-size: 0.8rem;
vertical-align: middle;
}
The simplest way is also here to use the flex box.
.flex-vertically {
height: 200px;
display: flex;
align-items: center;
}