CSS 背景裁剪

CSS 的 background-clip 属性定义了元素用于裁剪背景图像、颜色或渐变的背景区域。例如,

div {
 background-clip: content-box;
}

浏览器输出

CSS Background-Clip Content-Box Example Description

在此,background-clip 属性仅将背景应用于 content-box。内容框仅包含内容区域,而不包括元素的内边距或边框。


CSS background-clip 语法

background-clip 属性的语法是:

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

这里,

  • border-box:允许背景延伸到元素的边框后面
  • padding-box:允许背景延伸到元素边框的内部
  • content-box:背景被裁剪到元素的 content-box
  • text:背景仅被裁剪到元素文本的后面

CSS 背景裁剪示例

让我们通过一个使用不同值的 background-clip 示例。

<!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;
}

浏览器输出

CSS Background Clip Example Description

在上面的示例中,background-clip: text 指定内容是透明的,背景仅在文本边界内可见。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战