问题
If I use both background-origin: content-box; and background-size: cover; on an element with some padding. The background image still covers the bottom padding (in latest versions of Safari, Chrome, Firefox and 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
Is this the correct behaviour? If so, why (am I missing something obvious here)?
回答1:
Yes, this is the correct behaviour. background-origin
simply shifts the background image. It doesn't modify the background painting area. You need to set background-clip
as well, otherwise its value remains as border-box
and any part of the image that exceeds the content area due to mismatched aspect ratios will bleed into the padding area:
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;
}
回答2:
There's a difference between background-origin
and background-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.
As you can see, the background-origin won't clip the image on the bottom edge, it will just make it start (as in placement) where you set its value. However, the background-clip will make it visible or not, will mask it according to the value you set.
More information on MDN:
- https://developer.mozilla.org/en-US/docs/CSS/background-clip
- https://developer.mozilla.org/en-US/docs/CSS/background-origin
来源:https://stackoverflow.com/questions/43043878/css-background-combining-content-box-with-cover