html - 如何让一个移动的 div 里面有一个固定覆盖的元素?

标签 html css

我正在尝试将菜单覆盖在图像上,但图像的容器是可变的。我不知道图像将在哪里或有多大。我如何在不知道在哪里设置左上角坐标的情况下将绝对/固定的东西定位在图像上?

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>

这是一个 example that doesn't work .您可以看到作为叠加对象的蓝色边框框如何被推到白色全跨度 div 下方。

如果我使用绝对位置,但是或固定位置,我得到 this .

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

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

在上面的示例中,我有一个固定的高度尺寸来处理宽度仅为 100% 的地方。

感谢您的帮助。

最佳答案

考虑使用伪类来完成此任务。无论 .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>

关于html - 如何让一个移动的 div 里面有一个固定覆盖的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37109739/

相关文章:

python - 使用 django 在 HTML 页面中显示数据库中的数据

JavaScript 错误 : 'undefined is not a function' when trying to remove and add class to li element

jquery - 填充可用宽度? (图片示例)

javascript - 固定内层在外层顶部,滚动外层时防止内层溢出到外层

css - 是否有可能让这个 SCSS 在 CSS 中工作?

javascript - While循环: Generated table rows and column inconsistency

html - 如何使用 CSS3 为表格背景设置白色渐变动画

javascript - jQuery BlockUI 元素阻止在 Chrome 上不起作用

html - CSS overflow-x 和空白效果不适用于 Firefox(但适用于 Chrome)

HTML 表格文本对齐(tbody 适配 thead)