CSS: Highly Customizable Text Underline

If you're not happy with the default text-decoration: underline, want to tweak the thickness of the underline or vertical space between the text and the underline, then you may want to the background trick introduced in this post. Medium is also using this kind of technique.

// use background image to draw the underline
// this way we can tweak the vertical space between text and underline
a {
  text-decoration: none;

  background-image: linear-gradient(to bottom, rgba(0,0,0,0) 50%, rgba(0,0,0,.6) 50%);
  background-repeat: repeat-x;
  background-size: 2x 2x;
  background-position: 0 22px;

A quick demo of how it looks like:

text underline with background image demo

One caveat of this approach is, the position and thickness of the underline is depending on the font size. So if you're using a different font-size as I do in the demo, you may need to change the background-position to fit your design.

Also if you want to apply it to different part of your page which all have different font-size, you will need to figure out the exact size for each part.

In my blog I'm using SCSS variables to document this behavior.

$post-font-size: 20px;
$underline-size: 2px;

background-size: $underline-size $underline-size;
background-position: 0 ($post-font-size + $underline-size);
June 06, 2016 css

Qihuan Piao

Qihuan Piao

(aka kinopyo) is Chinese based in Tokyo. Software writer. He shares stories inspired him this blog. His infamous line - "I feel calm when I kill those monsters, or people (in game)" shocks his friends deeply.
He also writes in Japanese and Chinese.