How to give gradient color to text using CSS.

How to give gradient color to text using CSS.

This is a short tutorial on adding gradient color to text or headers using CSS on a web page.

To give a gradient overlay over to text using CSS, we can use these three properties:

  • background-image
  • background-clip
  • text-fill-color

The background-image property is used to set one or more images to an HTML element.

Example: Set background to the body.

    background-image: url('image.jpg');

The background-clip property is used to set how far the background image or color extends beyond the element's border-box, padding, or content-box.

background-clip: border-box|padding-box|content-box|initial|inherit;

The text-fill-color property is used to set the fill color of the text. If it's not specified in your CSS, then it will use the value of the color property.

text-fill-color: color | initial | inherit;

Now to create a gradient overlay to the text we will use these three properties together on the text element in HTML.

First, let's create our header text with a class gradient-header.

    <h1 class="gradient-header">PROGRAMMING BASIC</h1>

Next, we will write the CSS for the class.

.gradient-header {
  background-color: red;
  background-image: linear-gradient(to bottom right, red, yellow);
  background-clip: text;
  -webkit-background-clip: text;
  -moz-background-clip: text;
  -webkit-text-fill-color: transparent;
  -moz-text-fill-color: transparent;

to bottom right in linear-gradient means, the direction you want your gradient to flow and red and yellow are the two colors for the gradient.

Since some browsers might not support linear-gradient clipped on top of text, so we have to use the background-color as a fallback for the background-image property.

Since different browsers use different rendering engines, we have to use the -webkit and -moz prefix with the CSS property to run the CSS styles properly in all browsers.

The -webkit prefix is used by Safari, Chrome, and Android browser rendering engine and -moz prefix is used by Firefox.



Edit mgc18x