Applying background image only on text using css

Applying background image only on text using css

2 min. read

HTML markup

<!DOCTYPE html>
<html>
	<body>
		<div>Webslake</div>
	</body>
</html>

CSS rules

div
{
	text-align:center;
	color: #3b3; /* Green */
	font:bold 100px Nunito;
}

@supports (background-clip:text) or (-webkit-background-clip:text)
{
	div
	{
		background-image:url('https://images.pexels.com/photos/533948/pexels-photo-533948.jpeg?w=940&h=650&auto=compress&cs=tinysrg');
		background-clip:text;
		-webkit-background-clip:text;
		background-size:cover;
		color:transparent;
	}
}

See result in the fiddle below

What we are doing is ...

  1. first, we are setting the color and font for the text
  2. secondly , we are telling the browser through our css code that " Hey ! if you support the background-clip:text or -webkit-background-clip : text property ", then apply this additional css ( css inside the @supports at-rule ) to the div element.

Click here to learn more about @supports at-rule

" background-clip : text property clippes the background-image to the textual part of div element.
In case if background-clip:text property is not supported by the browser then the text will appear in green color. "

Note

background-clip : text property is not widely supported across all the browsers.

Click here to read more about background-clip css property.

Write comments