Centering content with CSS
How to center a div has become a little bit of a joke in the web development community, and for good reason. Not only is it a common task, but it can also be a bit tricky to get right, especially when you're new to CSS. Luckily, modern CSS solutions exist for pretty much any scenario you might encounter.
Flexbox centering
Using flexbox to vertically and horizontally center content is usually the preferred method. All it takes is three lines of code in the container element to set display: flex
and then center the child element vertically and horizontally using align-items: center
and justify-content: center
respectively.
<div class="flexbox-centering"> <div class="content">Content</div> </div>
.flexbox-centering { display: flex; justify-content: center; align-items: center; }
Grid centering
Using the grid module is very similar to flexbox and also a common technique, especially if you are already using grid in your layout. The only difference from the previous technique is that you use display: grid
in the container element and then center the child element the same way as before.
<div class="grid-centering"> <div class="content">Content</div> </div>
.grid-centering { display: grid; justify-content: center; align-items: center; }
Transform centering
Transform centering uses, as the name implies, CSS transforms to center an element. It depends on the container element having a position: relative
, allowing the child element to utilize position: absolute
to position itself. Then left: 50%
and top: 50%
are used to offset the child element and transform: translate(-50%, -50%)
to negate its position.
<div class="transform-centering"> <div class="content">Content</div> </div>
.transform-centering { position: relative; } .transform-centering > .content { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
Table centering
Last but not least, table centering is an older technique which you might favor when working with older browsers. It depends on the use of display: table
in the container element, making it behave like a <table>
element. This allows the child element to use display: table-cell
, behaving like a <td>
, in combination with text-align: center
and vertical-align: middle
to center itself horizontally and vertically. Note that the parent element must have a fixed width
and height
.
<div class="table-centering"> <div class="content">Content</div> </div>
.table-centering { display: table; height: 100%; width: 100%; } .table-centering > .content { display: table-cell; text-align: center; vertical-align: middle; }