Center an element both horizontally and vertically with place-items CSS property

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

An ancient problem of centering items with CSS is finally (!) solved!

In this quick lesson we're going to learn how to use place-items CSS property in order to center an element both horizontally and vertically with a single line of code!

Tomasz Lakomy: [0:00] Over here, we have two divs. First up, there's a parent and also a child. We can see the result over here. We would like to achieve an effect that in the past was difficult with CSS. In other words, to put this child div right in the middle of the parent container. That is, to center it both horizontally and vertically.

[0:19] The usual way of achieving that would be to use the display, flex property, and then setting the justify-content to center and align-items to center. This can actually be done with a single line of code. If I remove those two and change the display to grid, I can use a property which is known as place-items, and set it to center.

[0:41] There we go. We have a child div which belongs right in the middle of this container. If I allow the user to modify the content of this child div, so for instance type in, "Hello egghead, this div stays center no matter what!" We can see that this child stays in the middle no matter the size of the content.

[0:59] You can read more about this CSS property on the MDN Web Docs. What is interesting is that the browser support is pretty much universal, apart from this one browser, obviously.

egghead
egghead
~ 39 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today