html - parent 使用 float 时 child 的绝对位置

标签 html css css-position z-index

我正在做一个设置,其中两个图像和一个文本容器并排使用 float left,但是我还需要在用户悬停时使用带有一些文本的覆盖 div,但这会破坏显示。

这是我的 HTML 代码:

<div class="container">
  <div class="parent-container">
    <div class="child-container">
      <img src="http://blog.hdwallsource.com/wp-content/uploads/2016/02/solid-color-wallpaper-21953-22506-hd-wallpapers.jpg" alt="" />
      <div class="overlay">
        <p>Some text</p>
      </div>
    </div>
    <div class="child-container">
      <img src="http://www.pixelstalk.net/wp-content/uploads/2016/06/Solid-Color-HD-Wallpapers-For-Desktop-768x432.jpg" alt="" />
    </div>
    <div class="child-container-text">
      <p>hhohdoioadoasabs</p>
    </div>
  </div>
</div>

这是我的 CSS:

.parent-container {
  position: relative;
  width: 100%;
}

.child-container {
  float: left;
  position: relative;
  width: 30%;
}

.child-container img {
  position: absolute;
  height: 100px;
  width: 100%;
}

.child-container-text {
  background-color: #000;
  float: left;
  height: 100px;
  position: absolute;
  width: 40%;
}

.overlay {
  background-color: #FFF;
  opacity: 0.3;
  position: absolute;
  z-index: 999;
}

这是一个带有它的 CodePen:https://codepen.io/leofontes/pen/ORPJWd?editors=1100

知道为什么它们会堆积起来吗?我以前对叠加层使用过相同的绝对定位技巧并且有效,为什么 float 会破坏它?

谢谢

最佳答案

https://jsfiddle.net/37LsfmLa/ 有关工作示例,请参见 fiddle 。 (抱歉,我不知道 codepen 是如何工作的!)

你的问题含糊不清,但我相信这就是你要找的。你的代码的问题是你给了图像一个绝对位置,同时将它们放在一个 float 的 div 中。标准的 float 行为会折叠任何空的 div。它会将任何元素缩小到其内容大小。 您的元素设置了它们的 width,这应该可以解决该问题,但还有另一个问题:它们没有高度。结果:他们崩溃了。 -- 请注意,具有 position:absolute 的元素算作拉伸(stretch)其父元素的内容。

这就是你的问题所在。你需要给你的 div 一个静态高度才能使这样的东西工作,虽然我想知道为什么你的图像甚至有 position:absolute?但是,无论什么漂浮你的船。 (我不会在任何应该填充元素的图像上使用 position:absolute,但这只是我的偏好)

.child-container {
  float: left;
  position: relative;
  width: 30%;
  display: block;
  height: 100px;
}

^ 以上是修复它的内容。一个简单的 height 属性。

关于html - parent 使用 float 时 child 的绝对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39312578/

相关文章:

javascript - 服务器端事件开始/停止

html - 样式化 HTML-<li>List in <ol>list in <ol>list 使每个列表元素在屏幕左侧具有相同的差异(不是 margin-left!)

html - 使用响应式网页设计调整大小时,如何使元素消失?

javascript - 在 css 文件 href Javascript 中更改 css 类背景

html - header 显示一些我无法修复的奇怪间隙 - CSS

css - 如何用CSS反转标题和正文的 float 顺序?

javascript - "touch and feel"在自定义 HTML 下拉菜单

html - 如何将放置在 iFrame 内的 div 定位在屏幕中央

html - 相对于容器中父图像的缩放,如何缩放/移动容器中的子图像?

css - 如何在 Safari 的 flexbox 容器中居中固定内容?