CSS 背景。将内容框与封面相结合

CSS Background. Combining content-box with cover

如果我同时使用 background-origin: content-box;和背景大小:封面;在带有一些填充的元素上。背景图像仍然覆盖底部填充(在最新版本的 Safari、Chrome、Firefox 和 IE 中)

div {
  background-image: url('http://lorempixel.com/400/200/');
  background-origin: content-box;
  background-repeat: no-repeat;
  background-size: cover;
  border: 5px red solid;
  padding: 20px;
}

jsfiddle here

这是正确的行为吗?如果是这样,为什么(我在这里遗漏了一些明显的东西)?

是的,这是正确的行为。 background-origin 只是移动了背景图像。它不修改背景绘画区域。您还需要设置 background-clip,否则它的值将保持为 border-box,并且由于宽高比不匹配而超出内容区域的任何图像部分都会渗入填充区域:

div {
  background-image: url('http://lorempixel.com/400/200/');
  background-clip: content-box;
  background-origin: content-box;
  background-repeat: no-repeat;
  background-size: cover;
  border: 5px red solid;
  padding: 20px;
}

background-originbackground-clip 有区别。

The background-clip CSS property specifies whether an element's background, either the color or image, extends underneath its border.

The background-origin CSS property determines the background positioning area, that is the position of the origin of an image specified using the background-image CSS property.

如您所见,background-origin 不会裁剪底部边缘的图像,它只会使其从您设置其值的位置开始(如放置)。但是,背景剪辑会使其可见或不可见,会根据您设置的值对其进行屏蔽。

关于 MDN 的更多信息: