如何使一个移动的div内部有一个固定的覆盖元素



我试图将菜单覆盖在图像上,但图像的容器是可变的。我不知道图像会在哪里,也不知道它有多大。如果不知道在哪里设置左上角坐标,我怎么能在图像上定位绝对/固定的东西?

body {
  box-sizing: border-box;
  border: 0;
  padding: 0;
}
.main-container {
  height: 500px;
  width: 100%;
  background-color: #282828;
  padding: 0;
}
.moving-container {
  display: inline-block;
  margin-top: 100px;
  background-color: red;
  width: 100%;
  height: 100px;
}
.content {
  z-index: 1;
  width: 100%;
  height: 50%;
  background-color: white;
}
.overlay {
  z-index: 2;
  width: 300px;
  height: 150px;
  background-color: blue;
}
<body>
<div class="main-container">
    <div class="moving-container">
        <div class="content">
        </div>
        <div class="overlay">
        </div>
    </div>
</div>
</body>

这里有一个不起作用的例子。您可以看到作为覆盖对象的蓝色边框是如何被推到白色全跨度分区下面的。

如果我使用绝对位置,不管怎样,还是固定位置,我会得到这个。

我试图将图像设置为元素的背景,然后元素的内部将是菜单,但在不知道元素有多大的情况下,例如,固定的px值,背景图像不会出现(比菜单本身大)。

那我该怎么办?我遇到过翻译,但我以前没有实现过。

在上面的例子中,我有一个固定的高度尺寸,宽度只有100%。

谢谢你的帮助。

考虑使用psedoclass来完成此任务。无论.foo的尺寸如何,内部覆盖都将覆盖整个区域。

.foo {
  background: lightgray;
  width: 150px;
  height: 150px;
  position: relative;
}
.foo::after {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  content: '';
  display: block;
  background: rgba(255, 0, 0, 0.5);
}
<div class="foo"></div>

最新更新