Photo by Gradienta on Unsplash

Adding a Gradient to Text Using CSS

During my time at Flatiron, I’ve tried to squeeze in learning new CSS tricks wherever I could. Recently, I decided to explore how to give text a gradient with simple CSS.

For starters, let’s choose text to beautify. I’ll be adding a gradient to an <h1> in one of my recent Flatiron labs.

The first thing you’ll want to do is head over to your CSS file. I started by increasing the font size by 4rem to make the header more prominent. Then, I created a background for my text and gave it a linear gradient. Check out the color codes below. You can choose colors straight from VS Code or you can use a gradient generator like https://cssgradient.io/.

h1 {font-size: 4rem;background: linear-gradient(to left, rgb(132, 27, 202), rgb(231, 44, 44), rgb(240, 213, 94));}

At this point, the header will look like this:

So, now the task is to clip the gradient background to the text. You can achieve that by adding two more lines of code:

h1 {font-size: 4rem;background: linear-gradient(to left, rgb(132, 27, 202), rgb(231, 44, 44), rgb(240, 213, 94));-webkit-background-clip: text;-webkit-text-fill-color: transparent;}

The first “webkit” line of code is what actually clips the text on that gradient background. That means the gradient will be hiding behind your text. To fix that, add the second “webkit” line, which makes your text transparent and therefore makes the gradient visible. Your result should look like this:

Play around with different colors. Have fun!

Full Stack Software Engineer open to work. Experience in JavaScript, React.js, and Ruby on Rails.