Sometimes, we want to center horizontally div inside parent div with CSS.
In this article, we’ll look at how to center horizontally div inside parent div with CSS.
How to center horizontally div inside parent div with CSS?
To center horizontally div inside parent div with CSS, we use flexbox.
For instance, we write
<div id="parent" style="width: 100%">
<div id="child" style="width: 50px; height: 100px">Text</div>
</div>
to add nested divs.
Then we write
.parent-container {
display: flex;
justify-content: center;
align-items: center;
}
.child-canvas {
flex-shrink: 0;
}
to make the parent div a flex container with display: flex;
.
Then we center its content horizontally with justify-content: center;
.
Conclusion
To center horizontally div inside parent div with CSS, we use flexbox.