Hello there,
Centering content with CSS has historically been notoriously fiddly.
In the early days of the web you would use table and table cells just to get content centered both horizontally
and vertically.
Numerous ways of centering content has been used over the years. All of which have their own pros and
cons.
Then CSS
flexbox and
grid came along, which made centering
a lot easier; but I personally believe things can be even simpler and more intuitive.
Say you want to center an element within a box. Using
Tailwind
you would most likely do something like this:
flex justify-center items-center
That's not too bad. Three classes and we got what we want.
Now lets say we add an item and want to stack them horizontally, but position them to the right.
flex justify-end items-center
Easy enough!
Now all of a sudden we want to stack them vertically and keep them at the right hand side. That's easy
isn't it? We just add
flex-col!
flex flex-col justify-end items-center
Oh no! That doesn't work. See
flex-direction: column; flips the behaviour of
justify-content
&
align-items. For the experienced developer this is a no-brainer. We just
apply the correct classes:
flex flex-col justify-center items-end
And voilà!
But does it have to be this complicated? Do we have to use this many CSS properties to achieve something
this trivial?
The answer is no. There is a better way.