7 Ways to Escape CSS Hell

rylandking

Ryland @ Stackbit

Posted on October 12, 2021

7 Ways to Escape CSS Hell

Ever have this happen? lol

Funny meme about centering with css

Yeah, me too.

Here are the 7 ways to completely center whatever you want with CSS.

1. text-align: center;

This works only on display: inline & display: inline-block elements. Note also that it must be applied to the parent element.

Centering images and text with text-align: center css

2. margin: 0 auto;

This works only on display: block elements. And the element must have a width.

You can also specify just margin-left: auto and margin-right: auto if you want margins on the top or bottom.

Centering elements inside a div with margin: 0 auto css

3. vertical-align: middle;

This works only on display: inline & display: inline-block elements.

Centering elements inside a list with vertical-align: middle css

4. float: center;

lol (You cannot center floated elements.)

It's impossible to both horizontally and vertically center an element with float: center css

5. Centering absolute

When this comes up, use transform and 50% coordinates to center an absolutely positioned element.

Centering child divs of a position: relative parent div with css

6. Centering with flexbox

Flexbox has a bunch of different alignment classes that are always applied to the parent. This here will be completely centered within the box.

Centering elements inside a div with flexbox css

7. the one I forgot ;-)

Alt Text

💖 💪 🙅 🚩
rylandking
Ryland @ Stackbit

Posted on October 12, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related