If you want to center a div both horizontally and vertically, a CSS grid is the best choice.
In order to center a div using CSS grids, we have to make use of the align-content and the justify-content property. The justify-content
property centers the element horizontally while the align-content
property aligns it vertically inside the grid container.
Example:
.parent{ display: grid; height: 400px; align-content: center; /* aligns vertically */ justify-content: center; /* aligns horizontally */ border: 2px solid red; } .child{ width: 100px; height: 100px; text-align: center; padding: 20px; background: cyan; border: 1px solid; }
In the above example, each element inside the parent grid container will always be perfectly centered.