在CSS中的两种背景颜色之间叠加图片

时间:2020-08-24 13:58:09

标签: css

我的html就像

<div style='bg-gray'>
</div>
<img src='sample.png'>
<div style='bg-white'>
</div>

我的CSS就像

.bg-gray{
  background-color:gray;
}
.bg-white{
  background-color:white;
}

如何在两种颜色之间叠加图像,例如样本图像?

sample img

2 个答案:

答案 0 :(得分:0)

我为您创建了一个简单的示例。 我做了以下

style=更改为class=的样式仅用于内联样式。 我将.block类添加到div中,以便可以将它们一起定位

我将img移动到了第一个块,因此可以相对于该容器进行设置(这也是为什么我将position: relative添加到.block类的原因

之后,我绝对将图像相对于其父图像进行定位。因为我知道图像的高度将为150px,所以我可以给它bottom: -75px放置到一半。 然后,我将left: 50%; transform: translatex(-50%);添加到了容器的中间位置。

z-index: 2;紧随第二.block

.block {
  width: 100%;
  height: 300px;
  position: relative;
}

img {
  position: absolute;
  bottom: -75px;
  z-index: 2;
  left: 50%;
  transform: translatex(-50%);
}

.bg-gray{
  background-color:gray;
}
.bg-white{
  background-color:white;
}
<div class='block bg-gray'>
  <img src='https://via.placeholder.com/150'>
</div>
<div class='block bg-white'>
</div>

答案 1 :(得分:0)

请在选择器之后使用:-

.container{ padding:50px; height:300px;display: flex; justify-content: center; align-items: center; position:relative; z-index:5;}
.image-card{ position:relative;background:rgba(0, 0, 0, 0.3); text-align:center;}
.image-card:before{content:''; position:absolute; left:0px; width:100%; background:#99FFCC; height:50%; bottom:0px;}
<div class="image-card">
<div class="container"><img src='' width="200" height="200" style="background:#00CCFF;"></div>
</div>