Css 背景图片上的绝对定位元素(响应式)

Css absolute positioned element over background image (responsive)

我有一个响应式背景图片,因此它的宽度和高度会在调整屏幕大小时发生变化。在那个背景上,有一个绝对位置的元素。 现在,我的问题是,在调整屏幕大小时,绝对定位元素不会跟随其在背景图像上的位置...

这是我的 HTML 代码:

<section id="all">

  <div id="clicked1">
    <img class="box" src="factory.svg" width="100%" height="auto">
  </div>

</section>

CSS:

#all {
  width: 100%;
  height: 600px;
  position: relative;
  max-width: 1240px;
  background: url('beach_to_meter.svg') no-repeat;
}
#clicked1 {
  position: absolute;
  left: 27%;
  top: 28%;
  z-index: 100;
  width: 200px;
}
#clicked1 .box {
  width:14vw;
  max-width: 180px;
}

全屏是这样的: enter image description here 但是当屏幕变小时,绝对定位的元素会移动,就像这样: enter image description here 在此处输入代码

好吧,如果你想让一个图像出现在另一个图像之上的确切位置,你应该尝试 vw 和 vh(垂直宽度,垂直高度),我记得我做过这样的事情。 如果这不能解决您的问题,您应该使用 px,并使用 javascript 检测屏幕的大小,以便您知道将元素放在哪里。

我认为 CSS Transform-translate 对对齐元素很有帮助?也许你试一试?可以定义小图始终保持在大图高度的25%左右:

#clicked1 .box {
  transform:translateY(25%);
  transform:translateX(25%);
}

更多信息:https://www.w3schools.com/cssref/css3_pr_transform.asp。我没有你的图片来源,所以我无法尝试。但希望这会有所帮助。

在背景图片上搜索绝对定位元素时我想到了这个问题。希望我的询问能帮助到这里的其他人。

您可以使用 CSS 技巧的完美组合来获得在任何 device/display 图像上定位元素的良好行为方式:查看下面的代码片段

请注意,容器外的所有内容都按 vh 调整大小, 是视口高度。这也可以用 vw (视口宽度)来完成,我使用一些 media queries 来检测纵横比。

在容器内您可以安全地使用百分比。查看 .positioned 元素。元素大小在 vh(或 vw)中,位置始终在 top-left.

中的 %

该代码段还巧妙地 transform: translate(-50%, -50%); 使容器在视口上居中。

body {
  background-color: #404040;/* optional, to see position */
}
.container {
  background-image:    url(https://i.stack.imgur.com/2EzPF.jpg);
  background-size:     cover;
  height:90vh;
  width:90vh;
  background-repeat:   no-repeat;
  /* Center the container */
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* magic of transform */
}
.positioned {
  background-image:    url(https://i.stack.imgur.com/jpkTo.png);
  background-size:     cover;
  height:10vh;
  width:10vh;
  position: absolute;
  top: 58%; /* Positioned on bottom left corner of factory*/
  left: 33%; /* Positioned on bottom left corner of factory*/
  opacity: 0.8; /* optional, to see position */
}
.positioned:hover {
  background-image: none;  /* optional, to see position */
}
@media (max-aspect-ratio: 1/1) {
  /* css for vertical viewport */
  .container {
    height:90vw;
    width:90vw;
  }
  .positioned {
    height:10vw;
    width:10vw;
  }
}
<div class="container">
  <div class="positioned"></div>
</div>