brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: CSS place-items: center centers content on both axes in a grid

Css
~/tips/tip-css-place-items-center

place-items: center;

Centers items horizontally and vertically with one declaration on a grid container.

Centering something in CSS has a long history of jokes. With a grid container it is now one line, and the property is place-items.

.hero {
  display: grid;
  place-items: center;
  min-height: 100vh;
}

place-items is the shorthand for align-items (block direction) and justify-items (inline direction). With one value it sets both, so place-items: center equals align-items: center; justify-items: center;. With two values the first is align-items and the second is justify-items.

In a grid, every item that is smaller than its grid area gets centered in that area. If the container has a single cell, a single child lands in the middle of the box.

MDN lists the property as widely available, working across browsers since January 2020.

The caveat is flexbox. In a flex container, justify-items does not apply, so the second half of the shorthand is ignored and place-items: center only centers on the cross axis. For a flex container you still need this:

.row {
  display: flex;
  align-items: center;
  justify-content: center;
}

Also remember that the container needs some height to center in. A grid box that is only as tall as its content has nothing to center against, which is why the example above sets min-height.

Further reading: MDN: place-items

More Css tips CSS Overview in Chrome DevTools audits the colors and fonts of a page .notice:empty { .toast { article { counter-reset: h2; } .toolbar { All Css tips (66) All topics

Link