放大或更改视口大小时,元素会四处移动

Elements move around when zooming in, or while changing the viewport size

我到处寻找这个问题的解决方案,甚至查看了这里发布的一些类似问题,所以请不要将其标记为重复,因为我仍然无法弄清楚。

正如您在此处看到的,我试图将图像保持在红色容器上方的确切位置,但是当我放大或更改屏幕大小时,图像不在该位置我希望它是,它移动到页面的左侧。 (尝试自己放大页面或在编辑器模式下将幻灯片一直向右滑动,看看我的意思)。

我已经尝试了从绝对定位和相对定位到使图像成为内联块和块的所有方法。我不知道该怎么办? 请帮助我理解。 The code is here

.container {
  background: red;
  width: 50em;
  height: 50em;
  margin: 2em auto 3em auto;
  position: relative;
}

.image {
  width: 150px;
  position: relative;
  margin: 3em 0 0 13em;
}

.header {
  font-size: 3em;
  position: absolute;
  left: 6em;
  top: 1em;
}
<img class="image" src="https://i.imgur.com/zKdvwvz.jpg" alt="" />
<div class="container">
  <h2 class="header">Hello</h2>
</div>

您可以将代码包装在包装器中并为其定义 margin: 0 auto;。此外,您应该在容器边距中将 auto 替换为 0:

#wrapper {
  margin: 0 auto;
}

.container {
  ...
  margin: 2em 0 3em 0;
}

工作示例:

#wrapper {
  margin: 0 auto;
}

.image {
  width: 150px;
  margin: 3em 0 0 13em;
}

.container {
  background: red;
  width: 50em;
  height: 50em;
  margin: 2em 0 3em 0;
  position: relative;
}

.header {
  font-size: 3em;
  position: absolute;
  left: 6em;
  top: 1em;
}
<div id="wrapper">
  <img class="image" src="https://i.imgur.com/zKdvwvz.jpg" alt="" />
  <div class="container">
    <h2 class="header">Hello</h2>
  </div>
</div>


如果您希望包装器(带有容器)居中,您可以为包装器周围的元素定义 display: flex(可能是 main):

工作示例:

main {
  display: flex;
}

#wrapper {
  margin: 0 auto;
}

.image {
  width: 150px;
  margin: 3em 0 0 13em;
}

.container {
  background: red;
  width: 50em;
  height: 50em;
  margin: 2em 0 3em 0;
  position: relative;
}

.header {
  font-size: 3em;
  position: absolute;
  left: 6em;
  top: 1em;
}
<main>
  <div id="wrapper">
    <img class="image" src="https://i.imgur.com/zKdvwvz.jpg" alt="" />
    <div class="container">
      <h2 class="header">Hello</h2>
    </div>
  </div>
</main>