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

Viewed 10850


Whenever letter-spacing is applied to something with an underline or a bottom border, it seems like the underline extends beyond the text on the right. Is there any way to do prevent the underline from extending beyond the last letter in the text?

For example:

<span style="letter-spacing: 1em; border-bottom: 1px solid black;">Test</span>

Perhaps it'd be possible with a fixed width <div> and a border, but that is really not an option to surround every underlined element.

Thanks!

8 Answers

You can also use an absolute positioned pseudo element to achieve the underline, and counter the offset by specifying its with using the left and right property. Click below for an example.

<span style="letter-spacing: 5px; position: relative">My underlined text</span>

span:after {
    content: '';
    border-bottom:1px solid #000;
    display: block;
    position: absolute;
    right: 5px;
    left: 0;
}

https://codepen.io/orangehaze/pen/opdMoO

If you don't want to split the last letter of "Test", you can just wrap it with a span and do this:

span {
    letter-spacing: 1.1em;
    margin-right: -1.1em;
}

As you can see it even works with elastic units. If don't have a custom margin on a, you can skip adding the span and apply this style directly to a

It works wonders for me =)

Use clip-path to hide the extended underline. In your example:

span{
    clip-path: inset(0 1em 0 0);
}

The second value of the inset should be the same value as your letter-spacing.

Related