Center an element
In this recipe, you will see how to center one box inside another by usingflexbox andgrid, centering content both horizontally and vertically.
In this article
Requirements
To place an item into the center of another box horizontally and vertically.
Recipe
Click "Play" in the code blocks below to edit the example in the MDN Playground:
<div> <div>I am centered!</div></div>
.item { border: 2px solid rgb(95 97 110); border-radius: 0.5em; padding: 20px; width: 10em;}.container { border: 2px solid rgb(75 70 74); border-radius: 0.5em; font: 1.2em sans-serif; height: 200px; display: flex; align-items: center; justify-content: center;}
Using flexbox
To center a box within another box, first turn the containing box into aflex container by setting itsdisplay
property toflex
. Then setalign-items
tocenter
for vertical centering (on the block axis) andjustify-content
tocenter
for horizontal centering (on the inline axis). And that's all it takes to center one box inside another!
HTML
<div> <div>I am centered!</div></div>
CSS
div { border: solid 3px; padding: 1em; max-width: 75%;}.item { border: 2px solid rgb(95 97 110); border-radius: 0.5em; padding: 20px; width: 10em;}.container { height: 8em; border: 2px solid rgb(75 70 74); border-radius: 0.5em; font: 1.2em sans-serif; display: flex; align-items: center; justify-content: center;}
We set a height for the container to demonstrate that the inner item is indeed vertically centered within the container.
Result
Instead of applyingalign-items: center;
on the container, you can also vertically center the inner item by settingalign-self
tocenter
on the inner item itself.
Using grid
Another method you can use for centering one box inside another is to first make the containing box agrid container and then set itsplace-items
property tocenter
to center align its items on both the block and inline axes.
HTML
<div> <div>I am centered!</div></div>
CSS
div { border: solid 3px; padding: 1em; max-width: 75%;}.item { border: 2px solid rgb(95 97 110); border-radius: 0.5em; padding: 20px; width: 10em;}.container { height: 8em; border: 2px solid rgb(75 70 74); border-radius: 0.5em; font: 1.2em sans-serif; display: grid; place-items: center;}
Result
Instead of applyingplace-items: center;
on the container, you can achieve the same centering by settingplace-content: center;
on the container or by applying eitherplace-self: center
ormargin: auto;
on the inner item itself.