How to Center in CSS with Flexbox
There are many ways to center things in CSS but one of the easiest ways is to use CSS Flexbox. CSS Flexbox is a layout model that helps align one directional items. This short post we will take a look at how to center items not only horizontally but also vertically.
First we will start simple with wanting to center a single item in a parent container.
<section>
<div>1</div>
</section>
section {
width: 200px;
border: 1px solid #2d2d2d;
}
div {
color: #fff;
background: #2d2d2d;
padding: 12px;
display: inline-block;
}
To center the inner div
element we will make the parent a flex container.
section {
width: 200px;
border: 1px solid #2d2d2d;
display: flex;
justify-content: center;
}
By adding the display: flex;
property we make the section
element a flex container allowing us to adjust the layout of the div which is now a flex item. To center out item horizontally we use the justify-content: center;
. The justify-content
property allows us to position items along the main axis of the flex container. This the main axis can change dependent on the flex-direction.
The justify-content
property also has the start
, end
and stretch
that can position items along the main axis.
Centering Vertically
Now we have our element centered horizontally we can center our element vertically. Let's increase our parent container to be 200px high.
Not quite what we expect. By default flex items will fill vertical space of their parent element. To vertically center our div
we can add a single CSS property.
section {
width: 200px;
border: 1px solid #2d2d2d;
display: flex;
justify-content: center;
align-items: center;
}
By using align-items: center
we can vertically center all flex items to the parent container along the cross axis of the flex container.
The nice aspect of flexbox is the styles apply to all children of our flex container. If we add two more elements they all stay centered within the parent select
.
<section>
<div>1</div>
<div>2</div>
<div>3</div>
</section>
Check out the full working demo below and center all the things!