Child retain percentage position in parent on scale

45 Views Asked by At

I have a pin (red dot) over the image that has a percentage position set.

How can I retain the pin position relative to the image when re-sizing the parent wrap container? (resize the wrap container to see the issue)

#wrap{
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}
.pin{
  width:50px;
  height:50px;
  background:red;
  position:absolute;
  left:40%;
  top:40%;
}
img{
  display:block;
  width:100%;
}
<div id="wrap">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/1200px-Altja_j%C3%B5gi_Lahemaal.jpg"/>
  <div class="pin"></div>
</div>

1

There are 1 best solutions below

0
collab-with-tushar-raj On

I tried making it seamless but due to time constraints, I couldn't give my best shot. However, the pin is relative when resizing the wrap vertically and horizontally. Not sure how much I helped you with this.

Note: You can restrict the resizing up to a certain limit (minimum width and height) so that the pin does not go out of the image when a user tries to resize the wrap to almost "zero(0) dimensions".

window.addEventListener('resize', positionPin);

function positionPin() {
  const img = document.querySelector('img');
  const pin = document.querySelector('.pin');
  const imgWidth = img.clientWidth;
  const imgHeight = img.clientHeight;

  const pinLeft = imgWidth * 0.4; // 40% of the image width
  const pinTop = imgHeight * 0.4; // 40% of the image height

  pin.style.left = `${pinLeft}px`;
  pin.style.top = `${pinTop}px`;
}
#wrap {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  resize: both;
  overflow: auto;
}

.pin {
  width:50px;
  height:50px;
  background:red;
  position:absolute;
  left:40%;
  top:40%;

}

img {
  display: block;
  width: 100%; 
}
<div id="wrap">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/1200px-Altja_j%C3%B5gi_Lahemaal.jpg"/>
  <div class="pin"></div>
</div>