CSS underline and letter-spacing

1.8k views Asked by At

In a website menu, I have implemented some wishes of my customer concerning typography in CSS. She needs a different tracking on the font, no problem. But, she wants the active link to be underlined. As I have not implemented the code to target the active link, I just underlined them all to see how it would look. The CSS is as follows:

.main-navigation a {
    display: block;
    color: black;
    font-weight: bold;
    letter-spacing: 0.45em;
    line-height: 4.5em;
    text-decoration: underline;
    text-transform: uppercase;
}

And this is the result:

Menu of the website with styled links

The problem is that the letter spacing kind of messes up the underlining. I've drawn some vote magnets freehand circles to indicate the problem. The line starts nicely at the left side but is extended with the value of letter-spacing to the right.

Screenshot is from Firefox 25. Jsfiddle to see for yourself.

I could solve this using borders and using margins instead of line height, but is this fixable otherwise?

1

There are 1 answers

1
isherwood On BEST ANSWER

CSS Text underlining too long when letter-spacing is applied?

http://jsfiddle.net/isherwood/JWcGh/2

.main-navigation a:after {
  /* absolute positioning keeps it within h1's relative positioned box, takes it out of the document flow and forces a block-style display */
  position: absolute;
  /* the same width as our letter-spacing property on the h1 element */
  width: 0.45em;
  /* we need to make sure our 'mask' is tall enough to hide the underline. For my own purpose 200% was enough, but you can play and see what suits you */
  height: 200%;
  /* set the background colour to the same as whatever the background colour is behind your element. I've used a red box here so you can see it on your page before you change the colour ;) */
  background-color: #fff;
  /* give the browser some text to render (if you're familiar with clearing floats like this, you should understand why this is important) */
  content: ".";
  /* hide the dynamic text you've just added off the screen somewhere */
  text-indent: -9999em;
  /* this is the magic part - pull the mask off the left and hide the underline beneath */
  margin-left: -.40em;
}