CSS text gradient with fallback

Vladislav Ridvanovskiy
3 min readJul 7, 2020

--

Creating text gradients is a pretty common task for developers, isn’t it? But for some reason I often encounter the fact that developers are afraid to add gradients to text and look for excuses, just not to make them. I very rarely find solutions in production when it is used, but when I do, I rejoice.

What is the cause of fear? Cross-browser compatibility.

Let’s take a look at the implementation of the text gradient, which will be supported on almost all modern browsers, and for old ones, we will provide a fallback with @supports.

Let’s create a base structure:

Adding base styles, text centering, default color text.

Now let’s add a gradient to the title and check what we get as a result:

Result after adding background-image: linear-gradient(…);

WARNING: gradient on the text zone is affected by line-height, height of block.

As we can see, we get the text with solid color and background gradient under it. After that, we need to crop the background gradient to fit the boundaries of the text. We can do this with: background-clip: text;

Result after adding background-clip: text;

Now we need to make the gradient visible under the text, we can do this in two ways:

  1. color: transparent;
  2. -webkit-text-fill-color: transparent;

I recommend to use -webkit-text-fill-color: transparent; because
it will give us more flexibility for fallback later (with different colors).

This is much better. But what about old browsers? Let's process it with a support at-rule. We need to check if the browser supports -webkit-text-fill-colorand background-clip since these are the styles that we will be using.

Add @supports at-rule

As a result, we get a gradient on browsers that support these CSS properties correctly. If they are not supported —the default color will be used and gradient styles will be ignored.

Now let's create SASS mixin for this:

Creating mixin and using it

And here is final Codepen version:

Browsers support:

  • macOS/Windows and IOS/Android chrome = works;
  • macOS/Windows and IOS/Android Firefox = works;
  • IOS/Android UC browser = works;
  • macOS/IOS Safari = works;
  • EDGE = works;
  • IE = triggers fallback;

All was tested in last browser versions.

Thank you for your attention. Make the web different, give more eye candy to your users.

--

--

No responses yet