有没有一种方法可以在CSS的背景色之上叠加另一种颜色?

时间:2020-06-17 19:00:01

标签: css

我想在rgba(0,0,0,0.25)的顶部添加backgroundColor: "#0075FF"使其更暗。但是,有什么方法可以不使用混合色值来实现呢?注意:我也想避免使用在其顶部具有重叠元素的方法。

4 个答案:

答案 0 :(得分:1)

您可以对线性渐变使用此技巧:

background: linear-gradient(#f005, #f005), linear-gradient(#0f05, #0f05);

这样,您将使用两个带有alpha的渐变。诀窍是渐变的颜色以相同的值开始和结束。

答案 1 :(得分:1)

您可以做一个纯CSS方法,尽管它在主元素的顶部覆盖了一个伪元素。

*尝试将鼠标悬停在示例上。

.colored {
  background: #0075FF;
  width: 100px;
  height: 100px;
  position: relative;
}
.colored:hover:after {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.25);
}
<div class="colored"></div>

答案 2 :(得分:1)

您可以使用:before伪元素。

<div className="container">
    ....content
</div> 

.container {
    position: relative;
    background-color: #0075FF;
}

.container:before {
    content:"";
    display:block;
    position: absolute;
    height: 100%;
    width: 100%;
    top: 0px;
    left: 0px;
    background-color: rgba(0,0,0,0.25);
}

答案 3 :(得分:1)

您总是可以制作一个单独的容器,将元素放置在其中,然后在CSS中将新容器的大小与要放置在另一个容器上的大小相同。我使用了较低的不透明度,因此您可以透过顶部的颜色看到它,而当颜色不是紫色时,则看起来是紫色。 您可以调整容器的大小,然后根据需要使用放置方法。

.main {
  width: 200px;
  height: 200px;
  background: red;
  }
  
  .img {
    background-color: blue;
    width: 200px;
    height: 200px;
    z-index: 2;
    opacity: .5;
    }
<div class="main">
  <div class="img"></div>
 </div>