Add a colour gradient to text using CSS

Recently, I noticed Apple’s clever use of gradients in their headings, particularly highlighting the word “privacy.” This made me realize how powerful CSS gradients can be for adding visual interest to text, and I wanted to share how you can achieve this effect on your own website.

An example from Apple's. website showing a blue to red gradient on the word privacy.
Apple does a great job of putting attention on the word privacy.

I wasn't very familiar with the linear-gradient() css function, but it’s pretty simple once you understand the basics. Essentially, you define a direction using words like to left top or an angle like 90deg and specify start and end colors. After that, the text itself is clipped with a transparent fill, revealing the gradient underneath.

The CSS Code

Here's a simple example I'm applying to the h1 headings on the site:

h1 {
	background: -webkit-linear-gradient(0deg, #022640, #5786AB);
	-webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

This code creates a gradient that shifts from a dark blue (#022640) to a lighter metallic blue (#5786AB). The key properties here are:

  • background: Sets the gradient, where -webkit-linear-gradient is used to ensure cross-browser compatibility.
  • -webkit-background-clip: text: Clips the background (the gradient) to the text, so the text itself becomes the canvas for the gradient.
  • -webkit-text-fill-color: transparent: Makes the text fill transparent, allowing the gradient to show through.

Visual Ouput

A text gradient for the website h1 from dark blue to a metal blue.
Colour gradually shifts from a dark blue to a more metal blue. 

The gradient flows smoothly from left to right across the text, and even when the text wraps onto a new line, the gradient maintains its consistency across both lines. This gives a nice, unified effect, even if the text spans multiple lines.

Even with a line wrap the gradient goes left to right across both lines, so that Buffalo doesn't become brighter. 

Heading example with a dark blue to metal blue gradient
Here's an example from my homepage

Things to Keep in Mind

  1. Browser Support: Currently, the -webkit- prefix is necessary for full compatibility across most browsers (especially older versions of Chrome and Safari). You may also want to include a fallback for non-webkit browsers if needed.
  2. Gradient Directions: Experiment with different gradient angles and directions. For example, you can try to top right, 45deg, or other combinations to get various effects.
  3. Text Contrast: Make sure your gradient has enough contrast for readability, especially on light backgrounds. Darker gradients often work best on light-colored text.

By using CSS gradients on text, you can create eye-catching headlines and design elements with minimal effort. If you’re looking for a quick way to make your site more visually engaging, give this a try!