user4285211
user4285211

Reputation: 25

background-clip with background-size cover beaks cover?

I have a div with a background image. I want the image to always have at least a 1% left and bottom margin/padding. The container of the div is a dynamic absolutely positioned box which can have a size of 5% or 95% (and everything in between with CSS transition).

I chose to achieve this by putting the background-image on that div which has min-height of 5% and width of 100%. The background is not repeating, centred and set to be contained within the area (background-size: contain). I decided to go with a 1% padding and background-clip CSS property to content-box, which should mean that the background covers only the content which starts at 1% away from the border. I chose padding and not margin, because box-sizing is set to border-box, therefore a width 100% with additional padding would not increase the size of the div which is not the case with margin.

However this did not work as expected: When using background-clip: content-box together with background-size: contain, the background is contained within the border-box and not content-box and the padding cuts away the areas between the content and border. Example:

div {
  background-size: contain;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-image: url(http://www.ghacks.net/wp-content/uploads/2011/04/standard-google-image-search.jpg);
  float: left;
  width: 200px;
  height: 200px;
}

.clipped {
  border: 1px solid blue;
  padding: 20px;
  background-clip: content-box;
}

.normal {
  border: 1px solid green;
  padding: 20px;
  background-size: contain;
}
<div class="clipped">
</div>
<div class="normal">
</div>

So the questions are:

  1. Is this the normal behaviour?
  2. Where is this documented?
  3. What would be the solution to achieve what I need?

p.s. I am not English so apologies for possible mistakes or misconceptions. Also I will try to explain better in case you did not understand the issue.

Upvotes: 2

Views: 2110

Answers (1)

Asons
Asons

Reputation: 87201

  1. Yes, this is normal behavior. The content-box does not mean the image is sized within it, it means it gets clipped by it.

  2. https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip

  3. In below sample I used a pseudo class to achieve it

div {
  position: relative;
  float: left;
  width: 200px;
  height: 200px;
  border: 1px solid blue;
}

div::before {
  content: '';
  position: absolute;
  left: 20px;
  top: 20px;
  right: 20px;
  bottom: 20px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-image: url(http://www.ghacks.net/wp-content/uploads/2011/04/standard-google-image-search.jpg);
}
<div>
</div>

Upvotes: 1

Related Questions