html - 当 parent 有背景颜色时,图像不显示线性渐变

标签 html css

我有一个带有背景颜色的父 div.parent:白色和一个带有图像的 div。

我在 div.img-container 上设置了线性渐变

我需要的是有一个背景颜色为白色的容器,图像上有一个背景线性渐变。我需要两个“ parent ”。我不知道我错过了什么,当我只有一个 div 时它工作正常..

.parent{
  background-color:grey;
}

.img-container{
  height:200px;
  width:200px;
background: linear-gradient(to bottom, rgba(0, 0, 0, 0.30) 0%, rgba(0, 0, 0, 0.75) 100%);
margin:auto;
}

.my-img{
  display:block;
  position:relative;
  width:200px;
  height:200px;
  z-index:-1;
}
<div class="parent">
  <div class="img-container">
	  <img class="my-img" src="http://image.noelshack.com/fichiers/2016/05/1454345014-capture-d-ecran-2016-02-01-a-17-43-28.png">
  </div>
</div>

最佳答案

一个简单的解决方案是使用伪元素,而不会混淆 z-index 和主元素/父元素上的绝对定位。

这样它将与其余内容很好地融合。

.parent{
  background-color:grey;
}
.img-container{
  height:200px;
  width:200px;
  margin:auto;
  position: relative;
}
.img-container:after{
  content: " ";
  position: absolute;
  left: 0;
  top: 0;
  right:0;
  bottom:0;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.30) 0%, rgba(0, 0, 0, 0.75) 100%);
}
.my-img{
  display:block;
  width:200px;
  height:200px;
}
<div class="parent">
  <div class="img-container">
    <img class="my-img" src="http://image.noelshack.com/fichiers/2016/05/1454345014-capture-d-ecran-2016-02-01-a-17-43-28.png">
  </div>
</div>

关于html - 当 parent 有背景颜色时,图像不显示线性渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35135899/

相关文章:

html - 如何在 CSS 中组合通配符和非选择器

css - react 动态 CSS

javascript - react :Uncaught TypeError: Cannot read property 'set' of undefined

javascript - 导航栏是垂直的而不是水平的

jquery - 防止在html中加载图像

html - LinkedIn 网站分享始终显示 1 分钟阅读

c# - 不支持 WPF 调用脚本?

javascript - 在 Canvas 中制作弧形动画的最佳方式

html - 即使前一天的高度设置为自动,Div 仍与下方重叠

html - 超链接和有效的 W3C 标记