【问题标题】:How to make a moving div have a fixed-overlayed element inside?如何让一个移动的 div 里面有一个固定的覆盖元素?
【发布时间】:2016-05-09 15:39:32
【问题描述】:

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

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%。

感谢您的帮助。

【问题讨论】:

    标签: html css


    【解决方案1】:

    考虑使用 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);
    }
    &lt;div class="foo"&gt;&lt;/div&gt;

    【讨论】:

    • 选择器后面那个我不熟悉?不确定双冒号在 CSS 使用中的含义。事实证明,我可以在相对位置内使用绝对位置来做到这一点,gahhh ...我的意思是我很高兴找到了解决方案,但是伙计...如果您没有回答这个问题,将被删除。感谢您的意见。
    • 你应该阅读一些关于 CSS 伪类的知识。您将立即使用那些双 ::developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
    • 我想我可能已经看到它们用于悬停选择器之类的东西,但不确定。感谢您的链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 2011-11-27
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多