4.5.7 背景起始位置
优质
小牛编辑
133浏览
2023-12-01
默认情况下,背景图像从元素的 padding 区域的左上角开始显示。然而,有时候却希望背景图像从边框的左上角、或内容区的左上角开始显示。
这时,就可以通过 background-origin属性来设置背景图像的起始显示位置,可选值有 border-box | padding-box | content-box,默认值为 padding-box。
border-box 表示背景图像从 border 区域的左上角开始显示,当为边框设置透明度后,背景图像和边框相叠加,透过边框可以看见背景图像。padding-box 表示背景图像从 padding区域的左上角开始显示。content-box 表示背景图像从 content区域的左上角开始显示。当内边距为0时,padding-box 与 content-box 的效果相同。
这里对每个取值定义了一个类,然后分别应用到一个容器,来看看 background-origin属性在不同取值下的表现。代码如下:
div {
width: 120px;
height: 90px;
padding: 20px;
border: 10px dashed #888;
background-color: yellow;
background-repeat: no-repeat;
background-image: url(img/bg.gif);
}
.border-box {
background-origin: border-box;
}
.padding-box {
background-origin: padding-box;
}
.content-box {
background-origin: content-box;
}
<div class="border-box"></div>
<div class="padding-box"></div>
<div class="content-box"></div>
这里把边框设置为很粗的虚线,并把背景色设置为黄色,以便能够清楚看到背景色或背景图像延伸到边框下的情况。上述代码的运行结果如图 4‑34 所示:

从上图可以看到,background-origin 属性只能控制背景图像的表现,不能控制背景色的表现,背景色始终是从元素的边框开始显示。