【问题标题】:Position element over image element but the image changes size with the window将元素定位在图像元素上,但图像随窗口改变大小
【发布时间】:2024-01-17 07:11:01
【问题描述】:

我有一个将大小更改为窗口大小的图像,我需要在其上放置一个元素(锚标记),以便它始终相对于图像位于同一位置。该图像不是背景图像,而是 HTML 元素。

这个问题非常相似,但适用于图像是背景图像的情况。 Position element over background image. But the BG img changes size with the window. CSS

<img src="images/img.jpg" >
<a href="3">Link that should be over the image in a certain location.</a>

【问题讨论】:

标签: javascript jquery html css css-position


【解决方案1】:
<div class="wrapper">
    <img src="images/img.jpg">
    <a href="3">Link that should be over the image in a certain location.</a>
</div>

<style>
    .wrapper {
        position: relative;
    }

    a {
        position: absolute;
        top: 10%;
        left: 10%;
    }
</style>

【讨论】:

  • 标签可以做包装吗?
  • 没有。这里的重点是包装器从图像中获取大小,因此您的 元素可以相对于它定位。
  • 谢谢。其他作者在原始评论中首先回复并创建了 codepen 示例。您的回答很有帮助!
【解决方案2】:

将图像等包裹在一个收缩包装的 div 中,并以此为基础定位。

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.map {
  margin: 10px;
  border: 5px solid red;
  position: relative;
  display: inline-block;
}
.map img {
  max-width: 100%;
  display: block;
}
.box {
  width: 5%;
  height: 5%;
  background-image: url(http://www.clker.com/cliparts/W/0/g/a/W/E/map-pin-red.svg);
  background-position: top center;
  background-repeat: no-repeat;
  background-size: contain;
  position: absolute;
}
#pin-1 {
  top: 25%;
  left: 36%;
}
.box:hover > .pin-text {
  display: block;
}
.pin-text {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 75%;
  white-space: nowrap;
  display: none;
}
.pin-text h3 {
  color: white;
  text-shadow: 1px 1px 1px #000;
}
<div class="map">
  <img src="http://connect.homes.com/wp-content/uploads/2012/05/200392710-0012.jpg" alt="" />
  <div id="pin-1" class="box">
    <div class="pin-text">
      <h3>My House</h3>
    </div>
  </div>
</div>

Codepen Demo

【讨论】:

  • 感谢您的第一次回复和codepen演示!为了简化更多初学者程序员,我建议从答案中删除一些不相关的 HTML 和 CSS,以获得更基本的示例。
【解决方案3】:

你的意思是这样的吗?

    .image { 
       position: relative; 
       width: 100%; /* for IE 6 */
    }
    
    a { 
       position: absolute; 
       top: 20px; 
       left: 0; 
       width: 100%; 
    }
<div class="image">
    
          <img src="http://kingofwallpapers.com/grey/grey-001.jpg"/>
          
          <a href="3">Link that should be over the image in a certain location.</a>
    
    </div>

【讨论】: