To center a div using CSS flexbox, we have to first make the parent of the div element a flex container. To do this we have to apply display: flex;
property on the parent element. This will make the parent of the div element a flex container.
The items that are inside of the flex container are called flex items.
Now, apply the justify-content: center;
and align-items: center;
properties on the same parent element which we made the flex container.
The justify-content property aligns all the flex items inside the flex container horizontally while the align-items property aligns all the flex items vertically.
Example:
.parent{ display: flex; height: 400px; align-items: center; /* aligns vertically */ justify-content: center; /* aligns horizontally */ background: #9020e6; } .child{ width: 150px; height: 150px; text-align: center; padding: 20px; background: cyan; }