DEV Community

Cover image for How to center things in CSS ๐Ÿ’˜

How to center things in CSS ๐Ÿ’˜

Jayesh Tembhekar โšก on March 08, 2020

Yo devs ! ๐Ÿ”ฅ A quick guide on "How to center things in CSS" ๐Ÿ™Œ Most of the time, you write great CSS code from colors to complex animati...
Collapse
 
danielpdev profile image
danielpdev • Edited

You could also use the old style:

#content {
margin: 0 auto;
}

but this works only on block elements, so just add display: block; for inline elements.

Thanks for sharing!

Collapse
 
alvaromontoro profile image
Alvaro Montoro

That would only center horizontally though.

Collapse
 
danielpdev profile image
danielpdev

Yes, that's right.
Although, to align both horizontally and vertically you can also use margin in combination with position.

here is an example

Collapse
 
tobiassn profile image
Tobias SN

I generally use this website: howtocenterincss.com

Collapse
 
marklchaves profile image
mark l chaves • Edited

Nice.

Just to add, I usually give the flex container the responsibility of aligning its children. E.g.

<section>
  <div id="object"></div>
  <div>Hello World!</div>
</section>
section {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center; /* To vertically align all items added to the flex--not just one. */
}

Then any time you add another child, they will automagically align in the centre. In the example above, the children will align in one column because I specified flex-direction: column;.

Demo on CodePen.


Question @mindset ,

Why define the .element class twice on top of each other? Is there an advantage to that?

Here's how I would have done it.

Collapse
 
mindset profile image
Jayesh Tembhekar โšก

Not an advantage, just to separate main transform properties for easy understanding ๐Ÿ˜…

Collapse
 
marklchaves profile image
mark l chaves • Edited

Ok. Cool. I typically don't see that style unless it's a mistake. That's why I asked.

If you want to be more OO-like, I would delegate alignment to another class. Then add that class to the class list in the HTML. Like what I've shared with you above. Similar to multiple inheritance.

Then .demo-box and .centre-me are reusable.

Thanks!

Collapse
 
ziizium profile image
Habdul Hazeez

With CSS Grid:

.selector {
    display: grid;
    place-items: center;
}

I wrote about it in the following post:

Collapse
 
zarabotaet profile image
Dima • Edited

display: flex for parent
margin: auto for centered block

Collapse
 
adisreyaj profile image
Adithya Sreyaj

Flex for life ๐Ÿงก

Collapse
 
khaleddiz profile image
Khaled Breaker

just add to the parent div {

display: flex;
justify-content: center;
align-items: center;

}