Centering
Let's review the CSS centering methods.
Centering
Centering is the act of putting something in the middle of a page. It’s often much easier said than done! This is because there are many different ways to center elements. The way to do it is determined by whether we’re centering horizontally, vertically, or both!
In this lesson, we’ll look at how to do it best in each scenario.
Horizontal centering
Inline elements
Inline elements such as text can be centered horizontally with the text-align
property:
p {
text-align: center;
}
This works for inline
, inline-block
, inline-flex
, inline-table
, and so on.
Block elements
Block-level elements can be centered if both their margin-left
and margin-right
properties are set to auto
(assuming the element has a width). It’s often done with the margin
shorthand:
.element {
margin: 0 auto;
}
However, the modern way to center block-level elements (anything that isn’t text) is to use Flexbox! This horizontally centers any element inside the .container
element.
Get hands-on with 1200+ tech skills courses.