Centering
with grid
This is based on an article by Cory Rylan. The whole point is about centering with grid. I didn't think this would work with no width setting on any of the child divs. So I had to try it myself.
The test here is using grid without grid-template-columns
to centre things.
The lower examples are from ishadeed.com.
2. This box has several items. All you need do is add this line to the above:
grid-auto-flow: column;
You might also want a gap here:
gap: 4px; /* this only works w Firefox and Chrome - July 2020 */
3. For this box it’s the same except for justify-content
and align-content
. Instead justify-items
and align-items
are used. (NB. align-content
works the same here).
.parent {
display: grid;
grid-auto-flow: column;
justify-items: center;
align-items: center;
}
4. From an article on Smashing Mag: this uses display: grid
and place-items: center
. You can also use place-content: center;
which aligns items closer together.
.parent {
display: grid;
place-items: center;
}
5. This adds align-content: center
and gap: 4px
.parent {
display: grid;
place-items: center;
align-content: center;
}
6. This is the same as 4. but with only one item. This is a great way to centre with just two lines of code.
.parent {
display: grid;
place-items: center;
}
7. This can use flexbox or grid. Simply make the container a flex OR grid container (display:flex
or display: grid;
) and set the child's margins to auto.
This has no child element, it's just text.
.container {
text-align: center;
line-height: 250px; /* the value is equal to to container height */
}
This has no child element, it's just text.
.container {
display: table-cell;
vertical-align: middle;
}
This doesn't work here because this method won't work on grid or flexbox items. The outer needs to be set to display: table;
to work, rather than flex
or grid
. Nor will it work inside floated elements.
?
Conclusion
There are multiple ways to centre objects in CSS now. Factors to consider are whether you are centering one element, multiple elements or just text.
See also: Page 35 and an article over on CSS Geek.
1. On the parent of the first box the only CSS is: