Background image on text css effect

programming
Background image on text css effect

Background image on text is a very cool thing that you can do with HTML and CSS.

This effect is achieved using background-clip CSS property which is not widely supported across browsers so this effect might not work in all browsers.

Here's how it is done

HTML markup

<section id="text">TheWebCross</section>

Styling

Some basic styling for text

#text {
    display: block;
    color: #000; // Black color
    font: bold 80px Helvetica;
    text-align: center;
    margin: 40px 0;
}

Output of above HTML and CSS

See the Pen Text background-image 1 by TheWebCross (@thewebcross) on CodePen.

Below is the main part which adds background image on text.

@supports (background-clip:text) or (-webkit-background-clip:text){
    #text {
        background-image: url('Image URL');
        background-clip: text;
        -webkit-background-clip: text;
        background-size: cover;
        background-position: 50% 30%;
        color: transparent;
    }
}

Explanation

Here we are checking if the web browser supports any one of background-clip: text or -webkit-background-clip: text CSS properties then we will apply some additional styles to section(#text) element.

@supports (background-clip: text) or (-webkit-background-clip: text) is called @supports at-rule.

background-clip: text clips out the background image i.e it sets background image on the text, then we are adjusting size and position of section(#text) element using background-size and background-position CSS properties and finally we are setting the text color to transparent so that the background image applied to text can be seen.

In case if the browser does not support background-clip: text or -webkit-background-clip: text CSS properties the text will appear in black color without any background image.

Final output

See the Pen Text background-image 2 by TheWebCross (@thewebcross) on CodePen.

Thank you for reading :) please share this article with others.