Center align
Center alignment is one of the most discussed topic in CSS. Flexbox provides a easy and elegant way to solve this layout issue.
Example—Center aligning one item
<div class="container">
<div class="item">Center aligned.</div>
</div>
.container {
display: flex;
}
.item {
margin: auto;
}
The beautify of margin: auto
on the child items is that it automatically spread the items across the space with equivalent margins.
Example—Distribute multiple items in container
Thanks to the margin: auto
, the browser automatically distribute all the items inside the flexbox container equally.
<div class="container">
<div class="item">Item.</div>
<div class="item">Item.</div>
<div class="item">Item.</div>
</div>
Using align-items and justify-content
Alternatively, we can configure the alignment in the container by using the align-items
and justify-content
properties.
.container {
display: flex;
align-items: center;
justify-content: center;
}
.item {
/* No need to specify the alignment in children */
}
Example—Center aligning multiple items
By using the container’s alignment options, we can center align multiple items together.
html, body {
height: 100%
}
.container {
display: flex;
height: 100%;
align-items: center;
justify-content: center;
flex-direction: column;
}
.box {
height: 50px;
width: 300px;
margin: 0.2em;
}
You can find the live demo in the following link: