Home > Mobile >  How to resize child images proportionally to parent?
How to resize child images proportionally to parent?

Time:11-01

I have a big image, in other words, a map. I also have markers which are attached to certain positions of the map. In the following, you can see an example.

enter image description here

The map and the markers are wrapped in map-wraper and are positioned absolute.

HTML

<div class="map-wrapper">
  <img src="map.png" id="map" alt="Map">
  <img src="marker-1.png" id="marker-1" alt="Shop">
  <img src="marker-2.png" id="marker-2" alt="House">
</div>

CSS

.map-wrapper {
  position: relative;
}

#map {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

#marker-1 {
  position: absolute;
  top: 140px;
  left: 300px;
}

#marker-2 {
  position: absolute;
  top: 80;
  left: 40px;
}

The problem is when I resize the browser, the markers get out of position. I want the markers also to be resized proportionally to their parents. In this case map-wrapper.

I have tried this CSS trick, but it didn't help. https://css-tricks.com/scaled-proportional-blocks-with-css-and-javascript/

The reason why I don't just merge the markers with the map is that I want to give the markers hover effects.

Thanks in advance!

CodePudding user response:

Keep markers position on the map

Use relative percentage units for markers' topand left CSS properties.

This way the markers should stay at the same position relative to their relatively positioned parent container <div >.

#marker-1 {
  position: absolute;
  top: ...%;
  left: ...%;
}

#marker-2 {
  position: absolute;
  top: ...%;
  left: ...%;
}

Keep markers size relative to wrappers dimensions

Use relative percentage units for markers' height and set their width to auto.

This way the markers should keep the same size relative to their relatively positioned parent container's <div > height.

#marker-1 {
 ... some properties here...
 height: ...%;
 width: auto;
}

#marker-2 {
 ... some properties here...
 height: ...%;
 width: auto;
}

CodePudding user response:

Use calc() function instead to compute the position based on the browser size (%).

  • Related