Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Gradient-y text underlines using CSS

The usual way of applying an underline to the text is by using the text-decoration property which sets an underline (of the same color as the text) under the selected text.

Now, if you want to change the color of the underline, you can use the text-decoration-color property. And if you want some spacing between the text and the underline, you can further use the text-underline-position property with the value as under.

p {
  text-decoration: underline;
  text-underline-position: under;
  text-decoration-color: red;
}

Putting it all together, this is how a text would look like with a red underline beneath it.

See the Pen Text with simple underline by Amit Merchant (@amit_merchant) on CodePen.

Now, this is fine but that’s all you could do using these regular CSS underline properties.

What if you want something more fun and crazy? For instance, what about a gradient-y underline? How would you do that?

Well, to do that, you’ll need to dive into the world of pseudo-elements. A ::before pseudo-element to be precise!

Building The Gradient Underlines

The way you do it is first making the text’s position as relative. Also, you don’t need to use the underline properties (I mentioned previously) anymore.

p {
  position: relative;
}

Next, you need to use the ::before pseudo-element with the text (The <p> tag in our case) below which you need an underline and set its position as absolute.

And from there, tweak the top, left, height, and the `background properties to get the underline of your dreams.

p::before {
  content: "";
  position: absolute;
  top: 100%;
  width: 100%;
  left: 0;
  height: 5px;
  border-radius: 2px;
  background: linear-gradient(111.3deg, #9c27b0 9.6%, #00bcd4 93.6%);
}

Here’s how a gradient-y underline after putting it altogether would look like.

See the Pen Text with simple underline by Amit Merchant (@amit_merchant) on CodePen.

Looks fancy, right?

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?