Daniel
Daniel

Reputation: 215

CSS Background. Combining content-box with cover

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)?

Upvotes: 2

Views: 748

Answers (2)

Juan Ferreras
Juan Ferreras

Reputation: 2861

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:

Upvotes: 2

BoltClock
BoltClock

Reputation: 723729

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

Upvotes: 5

Related Questions