CSS: Why doesn't calc(contain * 0.66) work?

44 views Asked by At

I have two layered background images that need to be sized with contain in order to display correctly at all responsive breakpoints.

When I was specifying background-size using percentages I found that the images were getting clipped by the div bounds at some breakpoints. So I switched to using contain instead of %. This fixed the clipping.

However, I also want to scale down these background images to be smaller than 100% of the contain value.

Unfortunately, background-size: calc(contain * 0.66) doesn't appear to work.

How else can I approach this?

(I don't think adding white space within the image files themselves can be a solution, because their white space also needs to be responsive - one image occupies the upper left, and the other the bottom right of the div's background area. The div's width-height ratio and area vary considerably depending on the browser window's size.)

1

There are 1 answers

2
Hao Wu On

It is impossible to add calculation based on non-numeric value contain. But a very common work-around is to use pseudo element to mimic background image. Then you'll have better control to the dimensions of the pseudo element, here's an example:

You may try to resize the container on the botton left corner to see the effect

div {
  position: relative;
  resize: both;
  overflow: hidden;
  width: 200px;
  height: 160px;
  border: solid 1px black;
  background-color: gray;
  transform-style: preserve-3d;
}

div::before {
  /* the maximum size of the background-image */
  width: 66%;
  height: 66%;
  
  content: '';
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate3D(-50%, -50%, -1px);
  background: url(https://picsum.photos/640/480) center/contain no-repeat;
}
<div></div>