Hey, have you noticed that when the text has very wide tracking, it’s not centered?
See? Check this out. (the 0 is for the center point reference)
123454321
0
<style>.track-the-tracking {width: 100%; text-align: center; margin: 1rem 0;} .track-the-tracking h2 {letter-spacing: 1.5rem;}</style> <div class="track-the-tracking"> <h2>123454321</h2> <p>0</p> </div>
The 5 and oOo don’t properly align. Ugh.
This is because letter-spacing puts a space after each letter and it looks like this:
1_2_3_4_5_4_3_2_1_
When it should have been like this:
1_2_3_4_5_4_3_2_1
There are a couple of ways of trying to fix this problem.
Extra Spaces?
You could add an extra space in front of the first character with the
non-breaking space in front.
123454321
0
<h2> 123454321</h2>
So this looks slightly better. At least it’s not as skewed to one side.
However, as you can see, the 0 and the 5 don’t align properly.
Let’s try something else.
padding, inline-block
Inline-blocks are pretty great to use because they fit the content automatically. That means, you can add the letter-spacing amount to the left of the text, resulting in a block that has the equal amount of spacing on either side of the tracked out text.
123454321
0
That looks pretty well centered, right?
Here’s what it looks like with extra padding
So yeah, this is what it looks like:
123454321
You can see the text inside is properly centered
as opposed to this:
123454321
So, the padding really helps even it out. The CSS would look something like:
.proper-centering { display: inline-block; letter-spacing: 20px; padding-left: 20px; }
Use that in the html like:
<style> .track-the-tracking2 { width: 100%; text-align: center; } .track-the-tracking2 h2.proper-centering { display: inline-block; letter-spacing: 1.5rem; padding-left: 1.5rem; } </style> <div class="track-the-tracking2"> <h2 class="proper-centering">123454321</h2> <p>0</p> </div>
And there you have it. Much better centered text.
More uses
This applies to everything with generous tracking. Like buttons, here, have a look. This is with equal padding on the left and right. (letter spacing .7rem, padding 1rem on either side)
Here’s the same button but with paddings adjusted to center text. (letter spacing .7rem, padding 1rem on the left, and .3rem on the right side)
Looks like this:
a.centered-text { display: inline-block; letter-spacing: .7rem; padding: .8rem .3rem .8rem 1rem; }
Now, I know this might be something that could seem a bit nit-picky, and/or insignificant. And I understand that. Especially when the letter spacing is small, like 2 or 3 px. Then it’s hard to tell, and not many people notice. But when you want things to look “pixel perfect” and everyone you work with catch every little inconsistency (I thought I was bad, try working in a group where this is everyone’s JOB haha), then this becomes part of your regular SCSS mixin library. haha
So yeah, enjoy the well centered text.
[sc name=”learn css”]