CSS text gradient with fallback
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:
Now let’s add a gradient to the title and check what we get as a result:
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;
Now we need to make the gradient visible under the text, we can do this in two ways:
- color: transparent;
- -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-color
and background-clip
since these are the styles that we will be using.
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:
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.