How to Align Text Vertically Center in a DIV Using CSS

Louis.Z
3 min readJul 25, 2020

And horizontally, but everyone already know how to do that…

Grid + place-items

The solution is to use grid with place-items! place-items is the shorthand for writing both align-items and justify-items. It will also work if you use the latter. Learn more in-depth in the second section below.

Image illustration of CSS-Grid

Browser Support

CSS-Grid is supported in majority of the browsers, so is place-items. You will get 90.46% of users (only based on caniuse).

https://caniuse.com/#feat=css-grid
https://caniuse.com/#search=place-items

How does it work?

1. What is Grid?

My simplistic way is thinking about it as a grid box where you can define how many columns and rows and their length you would like using grid-template-columns and grid-template-rows.

Illustrated on Chrome DevTools

You can then define where to place your boxes within the grid using grid-column and grid-row. Use first figure as the start followed by “/” and where to end. grid-column is the shorthand for grid-column-start and grid-column-end. “-1” can be use to end at the last column. Another way is to indicate using “span” which indicate the number of grids for the box to cut across.

Illustration of the use of grid-column. Same goes for grid-row.

As the numbers indicate start and end, in fact, you can do it in reverse! 3 / 1 gives you the same result.

2. How Place-Items Works?

As mentioned above, place-items is the shorthand for writing both align-items and justify-items. In general, I only remember 3 main parameters to it — start, center, end. You can enter 2 parameters, if the second value is not set, the first value is also used for it. First parameter indicate where the items within the grid should align with vertically. As we can observe box A is top+left align, B is center-ly align and C is right+bottom align. There is all to it. You can play around using codepen. Try changing it to 2 different attributes.

A — start, B — center, C — end
Illustration of place-items

There is a lot more to what I used here, need to keep learning and try out to learn more.

--

--

Louis.Z

A passionate software engineer with strong background in web technology, product development and design architecture.