DEV Community

Cover image for How to kern lettering with SVG's dx attribute.
James Grubb
James Grubb

Posted on

How to kern lettering with SVG's dx attribute.

The devil is in the detail


The Kerning Game

Have you ever played the Kerning Game? I scored 72 out of 100, it's not easy and the scoring is a little subjective (that's my excuse 😀).

To kern a word is to adjust the space between letters and whilst it might be overkill to do this on every blog post <h1>, there are occasions where a wordmark might benefit from a little tlk (tender-loving-kerning)

In the above Codepen, the word Devil is set in Google's Akronim type-face. With the browser's default font-kerning settings - font-kerning: auto, notwithstanding, the first two letters D and e sit a little awkwardly, perhaps they are socially distancing?

dx to the rescue

"The dx attribute indicates a shift along the x-axis on the position of an element or its content." MDN Web docs

If we add a unitless value to the <text> dx attribute our Devil will shift along the x-axis by that units amount (and in relation to the svg's viewBox dimensions)

If you continue reading the MDN Web docs they describe using multiple dx values

If there are multiple values, dx defines a shift along the x-axis for each individual glyph relative to the preceding glyph. If there are fewer values than glyphs, the remaining glyphs use a value of 0. If there are more values than glyphs, extra values are ignored.

Let's help the D and e kiss and makeup by adjusting the individual spaces. I find that once you start tinkering you end up looking at all the letter spaces. This is what I ended up with.


As I mentioned, kerning is quite subjective and if you can, it's worth asking someone to look over your shoulder and get their kerning opinion.

!!!WARNING!!! once you start looking at kerning you will see bad kerning everywhere

Parade aligned

Conclusion

I hope you enjoyed this article. Of course, this method relies on using SVG in your markup. If you are using HTML, you could, for example, wrap each letter with a <span> with a display: inline-block class and adjust margins or relative positions. There are a number of other methods out there.

Usefull links

1 creating-web-type-lockup
2 11-kerning-tips
3 How to manipulate SVG text

Top comments (1)

Collapse
 
masakudamatsu profile image
Masa Kudamatsu

I just found out on my own the use of dx attribute for kerning, and reached this article after googling if anyone else has already discovered it. Glad to learn that I'm not alone.

I found tweaking a series of values for dx is a lot easier to kern than using <span> for individual characters. Also, if SVG is used inline in HTML, it's more readable for developers.

If we need an HTML semantic mark up like h1 and h2, maybe we can use the visually-hidden technique (my own article about it :-)) to hide it from sighted users (but not from search engines and screen reader users) and place a kerned title text in SVG instead.