The background-clip property in CSS is used to define the painting area of the background. This property determines whether the background color, image, or gradient extends underneath the border, padding, or content of an element.
The background-clip property can take several values. Here are the common values you can use:
Value | Description | Example |
---|---|---|
border-box | The background extends to the outer edge of the border (the default value). |
Border-box background clip
|
padding-box | The background extends to the edge of the padding box, but not underneath the border. |
Padding-box background clip
|
content-box | The background is clipped to the edge of the content box. |
Content-box background clip
|
text | The background is clipped to the foreground text. This is primarily used for text elements. |
Text background clip
|
Here's how you can apply different background clip values to your elements using CSS:
Example: Border Box
.border-box {
background-clip: border-box;
background-color: lightblue;
border: 5px solid darkblue;
padding: 20px;
margin: 10px;
}
This will render the background extending to the outer edge of the border.
.padding-box {
background-clip: padding-box;
background-color: lightgreen;
border: 5px solid darkgreen;
padding: 20px;
margin: 10px;
}
This will render the background extending to the edge of the padding box but not underneath the border.
.content-box {
background-clip: content-box;
background-color: lightcoral;
border: 5px solid darkred;
padding: 20px;
margin: 10px;
}
This will render the background clipped to the edge of the content box.
.text {
background-clip: text;
color: transparent;
background-color: lightpink;
background-image: linear-gradient(45deg, blue, red);
border: 5px dotted black;
padding: 20px;
margin: 10px;
font-size: 24px;
font-weight: bold;
}
This will render the background clipped to the foreground text.
Here are some important notes and best practices when using the background-clip property:
Here is a visual comparison of different background-clip values to help you understand their impact: