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...
              
        
    
  For further actions, you may consider blocking this person and/or reporting abuse
    
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!
That would only center horizontally though.
Yes, that's right.
Although, to align both horizontally and vertically you can also use
marginin combination withposition.here is an example
I generally use this website: howtocenterincss.com
Nice.
Just to add, I usually give the flex container the responsibility of aligning its children. E.g.
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
.elementclass twice on top of each other? Is there an advantage to that?Here's how I would have done it.
Not an advantage, just to separate main transform properties for easy understanding π
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-boxand.centre-meare reusable.Thanks!
With CSS Grid:
I wrote about it in the following post:
My WebDev Notes: Center page elements with CSS Grid
Habdul Hazeez γ» Apr 3 γ» 3 min read
display: flexfor parentmargin: autofor centered blockFlex for life π§‘
just add to the parent div {
display: flex;
justify-content: center;
align-items: center;
}