CSS background-origin:背景图的定位参考框

CSS 的 background-origin 选择用于定位和计算背景图尺寸的框。初始值是 padding-box。要从内容边缘开始,用 content-box;要以边框外缘为起点,用 border-box。

选择背景图的定位参考框

CSS background-origin 规范 定义了初始值,并规定该属性默认不继承。下面的蓝色矩形均使用 background-position: left top,不同之处是定位参考框。

值 定位参考 起点
border-box 边框的外侧边缘
padding-box 边框的内侧,也是内边距的外侧
content-box 内边距内侧的内容边缘
.border { background-origin: border-box; }
.padding { background-origin: padding-box; }
.content { background-origin: content-box; }

区分定位参考与背景绘制区域

更改定位参考框后,background-clip 仍控制背景的可见区域。background-origin: content-box 使图像从内容边缘开始。只要 background-clip 是 border-box,background-color 仍可能显示到边框下方。

给第一个框只添加 background-clip: content-box。蓝色矩形处于可见区域外,因此消失,但定位没有变化。比较完成后恢复 border-box。

比较三种框的图像起点

把代码保存为 UTF-8 编码的 background-origin-example.html 并用浏览器打开。示例用渐变作为背景图,无需外部文件。

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>背景图定位参考框</title>
  <style>
    body { font: 1rem/1.5 system-ui, sans-serif; margin: 1rem; }
    .demo {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr));
      max-width: 60rem;
      gap: 1rem;
    }
    .tile {
      box-sizing: border-box;
      width: min(100%, 260px);
      height: 110px;
      border: 10px dashed #253a4d;
      padding: 20px;
      background-color: #eef5fa;
      background-image: linear-gradient(#006c9c, #006c9c);
      background-position: left top;
      background-size: 60px 24px;
      background-repeat: no-repeat;
      background-clip: border-box;
    }
    .border { background-origin: border-box; }
    .padding { background-origin: padding-box; }
    .content { background-origin: content-box; }
  </style>
</head>
<body>
  <main>
    <h1>背景图定位参考框</h1>
    <div class="demo">
      <div>
        <p><code>border-box</code></p>
        <div class="tile border" aria-hidden="true"></div>
      </div>
      <div>
        <p><code>padding-box</code></p>
        <div class="tile padding" aria-hidden="true"></div>
      </div>
      <div>
        <p><code>content-box</code></p>
        <div class="tile content" aria-hidden="true"></div>
      </div>
    </div>
  </main>
</body>
</html>

每个框的边框是 10px、内边距是 20px。从外侧左上角测量,三个起点依次为 (0, 0)、(10, 10) 和 (30, 30)。第一个矩形部分位于虚线边框的下方。

计算百分比尺寸与位置

background-size 的百分比以定位框的宽度或高度为基准。外侧宽度为 260px 时,三个定位框分别为 260px、240px、200px。把下方的声明应用到 .tile,图像宽度分别为 130px、120px、100px。偏移可使第一个矩形避开边框。

.tile {
  background-size: 50% 24px;
  background-position: left 12px top 12px;
}

百分比位置还考虑图像的大小。水平方向为 100% 时,偏移等于参考框宽度减去图像宽度,因此两者的右边缘对齐。具体计算见 CSS background-position 百分比规则。

检查固定背景和看不出差异的情况

当某个背景层的 background-attachment 为 fixed 时,该层忽略 background-origin。在屏幕上通常以视口为基准定位,但元素的绘制区域仍可以裁剪可见部分。

如果三个框看起来相同,先确认边框和内边距是否都为零,再检查 background-origin 和 background-clip 的计算值。后写的 background 简写可以把省略的框设置重置为初始值。