Easy vertical alignment without flexbox
It is common to see display: flex
applied to just about everything. The addition of flexbox to CSS made vertical alignment significantly easier. Until now, the align-content
CSS property only worked with flexbox and CSS grid. Now that power has come to display: block
. display: block
is the default value of the ubiquitous <div>
element. Its handy to be able to center things without the need to write any additional CSS to change this default value.
If all we need is vertical centering, instead of:
.some-div {
display: flex;
align-content: center;
}
we can use the slightly terser:
.some-div {
align-content: center;
}
See the Pen align-content: center with display: block; by Ollie Williams (@cssgrid) on CodePen.
I’m a fan of keeping CSS as pruned and minimal as possible, so this is a nice addition to how layout works on the web.
This isn’t just about saving a line of code. It’s been common to use flexbox purely to center things, but flexbox also has other effects. Flexbox expands items to fill the available free space. This is often not what you want. Flexbox will also force items to line up in a row, even if they have a display value of block
. That’s often useful, but not always. One limiting factor of this new approach to centering is that we can’t use the gap
property as it only works with display
values of grid
or flex
, but margins still work well enough.
align-content
now also works for elements with a display
of table-cell
or list-item
:
See the Pen Untitled by Ollie Williams (@cssgrid) on CodePen.
Browser support
align-content
in block
layout is supported as of Chrome 123, Safari 17.4, and Firefox 125.