Vertically Centering Things
The Second Hardest CSS Problem
margin:0 auto will center a block horizontally, because auto means equal space on each side.
margin: auto auto has no extra effect, because the automatic top/bottom margin is 0.
Why? Is the W3C on drugs? Well, maybe. The bigger issue is CSS was originally designed
for relatively simple documents, and we keep pushing its limits.
There are a few curve-balls here:
Vertical Centering Notes
- Once upon a time, this was pretty much impossible. However, the new property
transform gives us a way
to hack around it.
- We could use
position: absolute; left: 50% to move the left edge on an object halfway across its container. However, this means its left edge is aligned to the center, and we need the center aligned to the center.
- You could compensate for this if you knew the exact width. But in a fluid crazy responsive world,
that's not a very realistic requirement.
transform (read about it on MDN) moves things around relative to themselves, no their container. so
transform: translateX(50%) will slide an element over by half its width.
- And that's our fix.
position:absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) will:
- Align the top and left edges to the center of the container
- Slide the element up and to the right by half its width and height respectively, so the centers
are aligned for each axis.
border-radius might be helpful for making things circles.
- Note that the letter are spaced out (
letter-spacing) and the font is all-caps.
- Never type words in all caps for aesthetics reasons - always used
- What is
text-transform, you ask? As usual, you should check on MDN.