How to create a multi-line text background effect

In this tutorial, we'll take a look at how to create a hover underline effect that works when your text spans on multiple lines.

We recently published the text background effects component, a collection of text backgrounds animated on hover that can be used with text spanning on multiple lines. That can be quite useful for links inside an article (where text can be on a single/multiple lines according to the viewport width). 

In this article, we'll see how to recreate one of those effects (the 'underline' effect).

Let's do this! #

Here's a video tutorial explaining how to create a multi-line text background effect. Feel free to skip the video if you prefer to read the article.

The component we build in this tutorial is based on the CodyHouse framework.

👋 First time you hear about the CodyHouse Framework?

The background-image CSS property sets an image as a background on an element; in combo with the linear-gradient CSS function, it can be used to create an image that is a combination of two or multiple colors.

For example, let's use the following linear-gradient as background image for our text element:

.text-bg-fx {
  background-image: linear-gradient(transparent calc(100% - 2px), currentColor 2px);

This image is composed of two colors (from top to bottom):

  1. transparent: it covers (100% - 2px) of the element;
  2. currentColor (the color of the text element): it covers 2px of the element.

The final background image is a 2px solid line at the bottom of the text element, similar to the default underline of link elements.

text-underline effect
Text underline effect created using the background-image property

Now, to animate this underline on hover, we can use the background-size property that sets the width and height of the background image; the width of the image can be 0% by default, and then changed to 100% when the text element is hovered:

.text-bg-fx {
  text-decoration: none;
  background-image: linear-gradient(transparent calc(100% - 2px), currentColor 2px);
  background-size: 0% 100%;
  background-repeat: no-repeat;
  transition: background-size .3s;

  &:hover {
    background-size: 100% 100%;

One important thing to notice is the use of the background-repeat property. By default, the background image is repeated along the x and y axes; changing the width of the background image would make no difference if it is repeated along the x axis.

Setting the background-repeat to no-repeat makes sure the image is not repeated and the animation works on hover.

That's it! The underline hover effect is now completed.

Feedbacks/suggestions? Get in touch on Twitter.