Achieving styled underlines in CSS

2016-12-09 | #css, #solution, #webdev

This is one of those miniscule effects nobody thinks should pose any kind of CSS problem, but indeed: Oh what a headache!

Just consistently styling the underline under a text independently from the font above is an oversight, which has not been implemented in the last two CSS revisions although being missed sorely from the very beginning of stylesheets. And besides being some sort of a bummer: the people designing the pages you have to build have no idea of this constraint.

But in fact, there is a fairly simple, if obscure solution working on all current major browsers.

The key is using a linear gradient as a background image on an inline element, so that the background follows line breaks. A linear gradient gives us precise control over position, color and thickness of the underline. The only downside being, that you cannot leave the line height with a background, preventing underlines far away from the base line.

Consider this Stylus mixin:

stylable-underline($color=COPYTEXT_FONTCOLOR, $weight=1px, $offset=0)

text-decoration: none

background-image: linear-gradient(to top, transparent, transparent $offset, $color $offset, $color ($offset + $weight), transparent ($offset + $weight))

background-repeat: repeat-x

Applying this mixin to an inline text element such as a span or a link will beautfully render an underline, having the $color you want it to have, being $width pixels thick and displaying at an $offset from the bottom end of the line height.

If you have to style your links as blocks, you can always introduce a span (class "caption" e.g.), that may then hold the underline correctly.