为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕斯709654 2023-02-24 15:20:51
我需要一个图像重叠另一个。但是第二张图片有背景色,我需要第一张图片介于第二张和第二张的背景色之间。有可能的?已经尝试创建一个新的“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>
查看完整描述

4 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

您不能为元素的某些属性赋予不同的z-index值。但是对于像 a 这样的某些元素,div您可以使用::before::after元素。你可以z-index在上面设置一个,有效地创建三个层。更多信息在这里

在这种情况下,您可以创建一个div中间img在里面的。然后添加一个::beforeand::after到那个div。给一个背景颜色和z-index-1。另一个是背景图像和z-index1。

在下面的示例中,我还在首字母周围添加了一些边距和边框div,以便您可以更好地了解发生了什么。

.image { 

    margin: 20px 0 0 20px;

    position: relative;

    border: 3px solid coral;

    width: 200px;

    height: 300px;

 }


.image::before,

.image::after {

    content: '';

    display: block;

    width: 200px;

    height: 300px;

    position: absolute;

}


.image::before {

    z-index: -1;

    background: cornflowerblue;

    top: 20px;

    left: 20px;

}


.image::after {

    z-index: 1;

    background: url("https://www.fillmurray.com/200/300");

    top: -20px;

    left: -20px;

}

<div class="image"><img src="https://www.fillmurray.com/200/300" /></div>


查看完整回答
反对 回复 2023-02-24
?
UYOU

TA贡献1878条经验 获得超4个赞

最后解决方案很简单。在样式中是第二个图像的双重定义。其中第一个只是部分评论。所以我的第一篇文章是这样工作的:


.secondimage img{

    max-width: 100%;

    height: auto;

    position: relative;

    top: -75px;

    margin: 5px;

        margin-bottom: 10px;

}

现在只需要找出如何关闭这个问题...谢谢 :)


查看完整回答
反对 回复 2023-02-24
?
慕娘9325324

TA贡献1783条经验 获得超4个赞

如果我理解你想要实现的目标,你可能应该将图像放在背景 div 中并将第二个图像放置在position: absolute:


<style>

  .mainRunner {

  position: relative;

}


.firstimage {

  position: relative;

  z-index: 2;

}


.secondimage {

  position: absolute;

  z-index: 3;

  top: 20px; /* use top and left values to place the image exactly where you want it over the first image */

  left: 20px

}


.background {

  position: relative;

  z-index: 1;

  background-color: #f2e5df; 

}

</style>



<div class="mainRunner">

  <div class="background">

    <img src="image1.png" class="firstimage" />

    <img src="image2.png" class="secondimage " />

  </div>

</div>

它将背景颜色设置为最后面的元素,然后在其顶部设置secondimage和firstimage。


查看完整回答
反对 回复 2023-02-24
?
慕村225694

TA贡献1880条经验 获得超4个赞

答案是否定的……没有办法将 z-index 专门定位到元素的背景,z-index 和所有其他 CSS 属性都作用于整个元素,而不仅仅是作用于它的背景。

你将不得不找到另一种方法来做到这一点,你有没有想过使用一个没有内容但图像大小相同的 div,然后只为那个特定的 div 设置背景颜色?


查看完整回答
反对 回复 2023-02-24
  • 4 回答
  • 0 关注
  • 95 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信