首页 > 解决方案 > 将 div 元素定位在绝对定位的图像上

问题描述

我有两张相互重叠的图像(一张绝对定位),因此我可以将鼠标悬停在一张上以查看另一张。我还想定位一个跨越顶部图像下 1/4 的“文本框”(一个带有彩色背景的 div,可以容纳一些简单的文本),但是,我在尝试定位时遇到了一些问题当它下面的图像已经绝对定位时,表示文本框。

我在下面附上了一个示例代码笔,以及我理想中的图像。有没有一种简单的方法可以用 HTML/CSS 做到这一点?

密码笔

<img src="img1.foo" class="img1" />
<img src="img2.foo" class="img2" />
<div class="textBar">Text bar here?</div>

示例图片

标签: htmlcss

解决方案


https://codepen.io/anon/pen/rKEEKb

添加到“标签”类的 CSS:

.tag {
  position: absolute;
  z-index: 3; /*place above the images */
  bottom: 0; /* put it at the bottom */
  padding: 20px; 
  width: 100%;
  background: lightblue;
  box-sizing: border-box; /* allow for padding to be included in width */
}

您也可以使用 css:hover 伪类https://developer.mozilla.org/en-US/docs/Web/CSS/:hover在不使用 jquery 的情况下执行此操作:

img.front:hover {
  opacity: 0;
}

推荐阅读