#css

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);
Qihuan Piao

Qihuan Piao

Originally from China and now living in Tokyo, I started this blog to practice English. Over the years, writing helped me find my own voice and explore thoughts about identity, life, and ordinary things that catch my curiosity. I mostly write for myself, but I love it when something here connects with someone else.

Meanwhile, what I wrote in Japanese

台湾旅行:両替は現地のほうが断然お得

May 28, 2016

Meanwhile, what I wrote in Chinese

许久不打台灯

June 9, 2016