Home > Net >  Scaling a portion of the background without changing background position
Scaling a portion of the background without changing background position

Time:06-08

(For this description please refer to the HTML and CSS portions below)

I have a container which contains a portion of an image (inner-container-1) I want to make this container smaller, scaling down the image within but getting the same portion of the image without changing the background-position coordinates (This means I can't just simple define background-size to be smaller as the coordinates would change in this case). I can't change the background-position because in different scenarios a different coordinate is used and these are all defined, if I scale down the background image I would create issues with the already defined background-position for other scenarios, therefore this must be done without changing background-position or image used.

More specifically, in this https://jsfiddle.net/GreenCarrot/tudzq8mx/42/ will see that inner-container-1 contains an image of a cat's eye, I want to shrink this container down to (50px x 50px) whilst showing the exact same portion of the image scaled down and without changing the (background-position: 585px 400px;).

HTML

<span id="outer-container">
  <span id="inner-container-1"></span>
  <span id="inner-container-2"></span>
</span>

CSS

#outer-container {
  width:300px;
  height:300px;
  position:static;
  display:flex;
}
#inner-container-1 {
  height: 100px;
  width: 100px;
  position: relative;
  border: 1px solid black;
  background-image: url(https://images.unsplash.com/photo-1583795128727-6ec3642408f8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8N3x8Y2F0c3xlbnwwfHwwfHw=&w=1000&q=80);
  background-position: center;
  background-position: 585px 400px;
}
#inner-container-2 {
  background-color: yellow;
  height: 50px;
  width: 50px;
  border: 1px solid black;
}

CodePudding user response:

You could scale it using transform, which would be pretty easy to figure in this case since you want to go from 100px to 50px so we just scale it by half.

#outer-container {
  width: 300px;
  height: 300px;
  position: static;
  display: flex;
}

#inner-container-1 {
  height: 100px;
  width: 100px;
  position: relative;
  border: 1px solid black;
  background-image: url(https://images.unsplash.com/photo-1583795128727-6ec3642408f8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8N3x8Y2F0c3xlbnwwfHwwfHw=&w=1000&q=80);
  background-position: center;
  background-position: 585px 400px;
  transform: scale(0.5);
}

#inner-container-2 {
  background-color: yellow;
  height: 50px;
  width: 50px;
  border: 1px solid black;
}
<span id="outer-container">
  <span id="inner-container-1"></span>
<span id="inner-container-2"></span>
</span>

  • Related