How to center an element using flexbox
January 9th 2024Summary
Centering stuff in CSS can be confusing at first. There are many ways to do it. Flexbox provides us with one of the simpler methods of centering things. This article shows how to use Flexbox to center DOM elements horizontally and vertically.
The Code
Center Horizontally
CSS
/* Please replace the css selectors with your code */
.parent-element {
display: flex;
justify-content: center;
}
Center Vertically
CSS
/* Please replace the css selectors with your code */
.parent-element {
display: flex;
align-items: center;
}
Center Horizontally and Vertically
CSS
/* Please replace the css selectors with your code */
.parent-element {
display: flex;
justify-content: center;
align-items: center;
}
The HTML
Here is html that all the above examples can be applied to.HTML
<div class="parent-element">
<div>one</div>
<div>two</div>
<div>three</div>
</div>