How to center a div in 2021
Damian Wróblewski - November 2021
Table of contents
Developers often focus mainly on javascript and forget about skilling up CSS, which can cause a lot of problems with potentially simply tasks. If you don't understand CSS fundamentals well, you will waste hours trying to fix quite simple issues. In this post we will cover one of the most memogenic CSS topic - how to center elements. There are several ways to do it.
Flexbox
Currently the most widely used method is flexbox:
1.parent {2 display: flex;3 justify-content: center; // horizontal centering4 align-items: center; // vertical centering5}
To place element in the middle of window horizontally and vertically, parent element has to be stratched across the entire width and height of window:
1.parent {2 width: 100vw;3 height: 100vh;4 display: flex;5 justify-content: center; // horizontal centering6 align-items: center; // vertical centering7}
OR
1.parent {2 width: 100vw;3 height: 100vh;4 display: flex;5}67.child {8 margin: auto;9}
Grid
To center elements you can use CSS grid too:
1.parent {2 display: grid;3 place-content: center; // horizontal and vertical centering4}
OR
1.parent {2 display: grid;3}45.child {6 margin: auto;7}
Position
A slightly older method is centering using the position property:
1.parent {2 position: relative;3}45.child {6 position: absolute;7 top: 50%;8 left: 50%;9 transform: translate(-50%, -50%);10}
In this case keep in mind that elements with position: absolute go out of document's flow and it may cause problems with positioning other nearby elements.
Margin
Because of the way the height of elements is calculated, with the margin property we can only center elements horizontally. Keep in mind that positioned element must have a specified width.
1.parent {2 width: 100vw;3}45.child {6 width: 100px;7 margin: 0 auto;8}
How to center a content?
To center a content inside a block element (e.g. text in a div) you can use text-align and vertical-align:
1.parent {2 text-align: center; // horizontal centering3 vertical-align: middle; // vertical centering4}
If you find inaccuracy in this post or you know another interesting way to solve this problem, contact me via social media or contact form 😉
Join the discussion