CSS Background Clip

CSS background-clip property defines the background area for an element to clip the background image, color, or gradient. For example,

div {
 background-clip: content-box;
}

Browser Output

CSS Background-Clip Content-Box Example Description

Here, the background-clip property only applies the background to the content-box. The content box only includes the content area and not the padding or border of the element.


CSS background-clip syntax

The syntax of the background-clip property is,

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

Here,

  • border-box: allows the background to extend behind the border of an element
  • padding-box: allows the background to extend inside the border of an element
  • content-box: background is clipped to only the content-box of an element
  • text: background is clipped behind only the text of an element

CSS Background-Clip Example

Let's see an example of background-clip with different values.

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <title>CSS background-clip</title>
    </head>

    <body>
        <h2>background-clip: border-box</h2>
        <div class="clip-border">Hello World</div>

        <h2>background-clip: padding-box</h2>
        <div class="clip-padding">Hello World</div>

        <h2>background-clip: content-box</h2>
        <div class="clip-content">Hello World</div>

        <h2>background-clip: text</h2>
        <div class="clip-text">Hello World</div>
    </body>

</html>
div {
    padding: 12px;
    border: 12px dashed;
    text-align: center;
    background-color: orange;
    font-size: 24px;
    font-weight: bold;
}

/*  clip the background area to border-box of the div*/
div.clip-border {
    /* default value */
    background-clip: border-box;
}

/* clip the background area to padding-box of the div*/
div.clip-padding {
    background-clip: padding-box;
}

/* clip the background area to content-box of the div */
div.clip-content {
    background-clip: content-box;
}

/* clip the background area to text background of the div*/
div.clip-text {
    background-clip: text;

    /* support for browser compatibility */
    -webkit-background-clip: text;

    /* set text color transparent and background color remains visible */
    -webkit-text-fill-color: transparent;
}

Browser Output

CSS Background Clip Example Description

In the above example, background-clip: text specifies the content to be transparent and the background remains visible only within the text's boundaries.

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community