place-items and place-content in CSS grid
26 place-items and its relatives
easyCentre every cell’s content in a grid with one declaration, centre the whole grid inside its box with another, and override a single cell. Write out what each shorthand expands to.
Stuck? Three hints, smallest first
- 1.
place-itemsisalign-itemsthenjustify-items; one value means both. - 2.
place-contentaligns the tracks inside the container;place-itemsaligns the content inside each cell. - 3.
place-selfis the per-item override.
<div class="board">
<div>one</div>
<div>two</div>
<div class="odd">bottom right</div>
<div>four</div>
</div>
.board {
display: grid;
grid-template-columns: repeat(2, 70px);
grid-auto-rows: 60px;
gap: 8px;
height: 160px;
place-items: center; /* align-items: center; justify-items: center */
place-content: center; /* align-content: center; justify-content: center */
border: 2px dashed #3055d8;
border-radius: 8px;
}
/* One cell breaks ranks. Block axis first, inline axis second. */
.odd {
place-self: end end;
}
.board > div {
padding: 4px;
background: #eef1fd;
border-radius: 6px;
font-size: 0.75rem;
text-align: center;
}
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
// One value applies to both axes; two are block axis then inline axis.
const pair = (value) => {
const parts = value.trim().split(/\s+/);
return parts.length === 1 ? [parts[0], parts[0]] : parts;
};
test('place-items: center means centre on both axes', pair('center'), ['center', 'center']);
test('two values are block axis first, then inline', pair('end end'), ['end', 'end']);
test('and they may differ', pair('start end'), ['start', 'end']);
test('the grid centres the content of every cell', /place-items:\s*center/.test(css), true);
test('and centres the tracks inside itself', /place-content:\s*center/.test(css), true);
test('one cell overrides both with place-self', /place-self:\s*end end/.test(css), true);
test('the container has a height, so place-content has room to work', /height:\s*160px/.test(css), true);
test('four cells', countTag(html, 'div'), 5);
Output
The pair to keep straight is place-items against place-content: the first aligns each item within its own cell, the second aligns the whole block of tracks within the container. They look interchangeable in a grid that fills its box, and they diverge the moment the tracks are smaller than the container — which is why this one has an explicit height. Both take one value for both axes or two, block axis first, and place-self is the escape hatch for a single item.