Advertisement

Quick Tip: Nonintrusive CSS Text Gradients

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

Though not completely cross browser compatible, there are ways to nonintrusively create pure CSS text-gradients with a bit of trickery. The key is to use a mix of attribute selectors, webkit-specific properties, and custom HTML attributes.


Final Simple HTML

<h1 data-text="Hello World"> Hello World </h1>

By using custom attributes, we can then hook into these values from within our stylesheet by using the attr() function.


Final CSS

/* Select only h1s that contain a 'data-text' attribute */
h1[data-text] {
	position: relative;
        color: red;
}

h1[data-text]::after {
	content: attr(data-text);
	z-index: 2;
	color: green;
	position: absolute;
	left: 0;
	-webkit-mask-image: -webkit-gradient(
		linear, 
		left top, left bottom, 
		from(rgba(0,0,0,1)), 
		color-stop(40%, rgba(0,0,0,0))
	);

Note: Paul referenced an even more succinct method in the comments. Be sure to check that out as well!

Advertisement