简体   繁体   English

如何根据父级按比例调整子图像的大小?

[英]How to resize child images proportionally to parent?

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.在下面,您可以看到一个示例。

在此处输入图片说明

The map and the markers are wrapped in map-wraper and are positioned absolute.地图和标记被包裹在map-wraper并且被定位为绝对的。

HTML 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 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 .在这种情况下map-wrapper

I have tried this CSS trick, but it didn't help.我试过这个 CSS 技巧,但没有帮助。 https://css-tricks.com/scaled-proportional-blocks-with-css-and-javascript/ 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!提前致谢!

Keep markers position on the map在地图上保持标记位置

Use relative percentage units for markers' top and left CSS properties.对标记的topleft CSS 属性使用相对百分比单位。

This way the markers should stay at the same position relative to their relatively positioned parent container <div class="map-wrapper"> .这样,标记应该相对于它们相对定位的父容器<div class="map-wrapper">保持在相同的位置。

#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 .对标记的height使用相对百分比单位,并将其width设置为auto

This way the markers should keep the same size relative to their relatively positioned parent container's <div class="map-wrapper"> height.这样,标记应该相对于它们相对定位的父容器的<div class="map-wrapper">高度保持相同的大小。

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

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

使用 calc() 函数根据浏览器大小 (%) 计算位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM