background-color 可以有不同于 img 的 z-index 吗?

我需要一个图像重叠另一个。但是第二张图片有背景色,我需要第一张图片介于第二张和第二张的背景色之间。有可能的?已经尝试创建一个新的“div 类”而不是 style="background-color"。现在我坚持这个:


.mainRunner {

  position: relative;

}


.firstimage {

  position: relative;

  z-index: 2;

}


.secondimage {

  position: relative;

  z-index: 3;

  top: -75px;

}


.background {

  position: relative;

  z-index: 1

}


<div class="firstimage" style="max-width: 1170px;"><img src="" alt="" title="" style="width: 100%;" max-width="1168" height="399" caption="false" /></div>

<div class="background" style="background-color: #f2e5df;">

<div class="secondimage">

<a href=""> <img src="" alt="" title="" /> </a>

</div></div>


慕斯709654
浏览 187回答 4
4回答

qq_笑_17

您不能为元素的某些属性赋予不同的z-index值。但是对于像 a 这样的某些元素,div您可以使用::before伪::after元素。你可以z-index在上面设置一个,有效地创建三个层。更多信息在这里。在这种情况下,您可以创建一个div中间img在里面的。然后添加一个::beforeand::after到那个div。给一个背景颜色和z-index-1。另一个是背景图像和z-index1。在下面的示例中,我还在首字母周围添加了一些边距和边框div,以便您可以更好地了解发生了什么。.image {&nbsp;&nbsp; &nbsp; margin: 20px 0 0 20px;&nbsp; &nbsp; position: relative;&nbsp; &nbsp; border: 3px solid coral;&nbsp; &nbsp; width: 200px;&nbsp; &nbsp; height: 300px;&nbsp;}.image::before,.image::after {&nbsp; &nbsp; content: '';&nbsp; &nbsp; display: block;&nbsp; &nbsp; width: 200px;&nbsp; &nbsp; height: 300px;&nbsp; &nbsp; position: absolute;}.image::before {&nbsp; &nbsp; z-index: -1;&nbsp; &nbsp; background: cornflowerblue;&nbsp; &nbsp; top: 20px;&nbsp; &nbsp; left: 20px;}.image::after {&nbsp; &nbsp; z-index: 1;&nbsp; &nbsp; background: url("https://www.fillmurray.com/200/300");&nbsp; &nbsp; top: -20px;&nbsp; &nbsp; left: -20px;}<div class="image"><img src="https://www.fillmurray.com/200/300" /></div>

UYOU

最后解决方案很简单。在样式中是第二个图像的双重定义。其中第一个只是部分评论。所以我的第一篇文章是这样工作的:.secondimage img{&nbsp; &nbsp; max-width: 100%;&nbsp; &nbsp; height: auto;&nbsp; &nbsp; position: relative;&nbsp; &nbsp; top: -75px;&nbsp; &nbsp; margin: 5px;&nbsp; &nbsp; &nbsp; &nbsp; margin-bottom: 10px;}现在只需要找出如何关闭这个问题...谢谢 :)

慕娘9325324

如果我理解你想要实现的目标,你可能应该将图像放在背景 div 中并将第二个图像放置在position: absolute:<style>&nbsp; .mainRunner {&nbsp; position: relative;}.firstimage {&nbsp; position: relative;&nbsp; z-index: 2;}.secondimage {&nbsp; position: absolute;&nbsp; z-index: 3;&nbsp; top: 20px; /* use top and left values to place the image exactly where you want it over the first image */&nbsp; left: 20px}.background {&nbsp; position: relative;&nbsp; z-index: 1;&nbsp; background-color: #f2e5df;&nbsp;}</style><div class="mainRunner">&nbsp; <div class="background">&nbsp; &nbsp; <img src="image1.png" class="firstimage" />&nbsp; &nbsp; <img src="image2.png" class="secondimage " />&nbsp; </div></div>它将背景颜色设置为最后面的元素,然后在其顶部设置secondimage和firstimage。

慕村225694

答案是否定的……没有办法将 z-index 专门定位到元素的背景,z-index 和所有其他 CSS 属性都作用于整个元素,而不仅仅是作用于它的背景。你将不得不找到另一种方法来做到这一点,你有没有想过使用一个没有内容但图像大小相同的 div,然后只为那个特定的 div 设置背景颜色?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript