Center an element with flexbox or grid in CSS
16 Centred two ways
easyCentre a box in its parent on both axes with properties on the parent. Then do it again with a single property on the child, and know when each is the better choice.
Stuck? Three hints, smallest first
- 1. On the parent:
display: flexplusplace-content: center. - 2. On the child:
margin: auto. Inside a flex container, auto margins absorb the free space on both axes. - 3. The parent still needs a height either way, or there is no vertical space to share out.
<div class="frame parent-centred">
<div class="box">Centred by the parent</div>
</div>
<div class="frame child-centred">
<div class="box auto">Centred by margin: auto</div>
</div>
.frame {
display: flex;
height: 110px;
margin-bottom: 10px;
border: 2px dashed #3055d8;
border-radius: 8px;
}
/* One shorthand for both axes: place-content is align-content plus
justify-content. */
.parent-centred {
place-content: center;
}
/* Nothing on the parent but display: flex. An auto margin in a flex container
eats all the free space in that direction, so all four centre the child. */
.box.auto {
margin: auto;
}
.box {
padding: 10px 16px;
background: #3055d8;
color: #ffffff;
border-radius: 6px;
font-size: 0.85rem;
}
7 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.
test('both frames are flex containers', /\.frame\s*\{[^}]*display:\s*flex/.test(css), true);
test('the first centres from the parent', /place-content:\s*center/.test(css), true);
test('the second centres from the child', /\.box\.auto\s*\{[^}]*margin:\s*auto/.test(css), true);
test('the frames have a height, or there is nothing to centre within', /height:\s*110px/.test(css), true);
test('no absolute positioning was needed', /position:\s*absolute/.test(css), false);
test('and no transform translate trick', /translate/.test(css), false);
test('two frames, one child each', countTag(html, 'div'), 4);
Output
place-content: center is align-content and justify-content in one, so it covers both axes in a single declaration. The margin: auto version is worth knowing for a different reason: in a flex container an auto margin absorbs all the free space on that side, which is why it centres when applied on all four sides and why it pushes an item to the far end when applied on one. That second behaviour is what the navbar exercise later depends on. Either way the parent needs a height — without one it shrinks to fit the child and nothing has room to move.