我有一个DIV,我想把一个模式作为背景。这个图案是灰色的。所以为了让它更漂亮一点,我想在上面加一个浅色透明的颜色“图层”。下面是我尝试过但没有成功的方法。有没有办法把彩色图层放在背景图像上?

这是我的CSS:

background: url('../img/bg/diagonalnoise.png');
background-color: rgba(248, 247, 216, 0.7);

当前回答

从css技巧…有一个一步的方法来做到这一点,没有z索引和添加伪元素-需要线性梯度,我认为这意味着你需要CSS3支持

.tinted-image {
  background-image: 
    /* top, transparent red */
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* your image */
    url(image.jpg);
}

其他回答

试试这个。对我有用。

.background {
    background-image: url(images/images.jpg);
    display: block;
    position: relative;
}

.background::after {
    content: "";
    background: rgba(45, 88, 35, 0.7);
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
}

.background > * {
    z-index: 10;
}

你也可以添加不透明度叠加颜色。

而不是做

background: url('../img/bg/diagonalnoise.png');
background-color: rgba(248, 247, 216, 0.7);

你可以:

background: url('../img/bg/diagonalnoise.png');

然后为不透明度颜色创建一个新样式:

.colorStyle{
    background-color: rgba(248, 247, 216, 0.7);
    opacity: 0.8;
}

将不透明度更改为低于1的任意数字。然后将此颜色样式设置为与图像相同的大小。它应该会起作用。

下面就是:

.background {
    background:url('../img/bg/diagonalnoise.png');
    position: relative;
}

.layer {
    background-color: rgba(248, 247, 216, 0.7);
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

HTML:

<div class="background">
    <div class="layer">
    </div>
</div>

当然,如果.background类中没有其他元素,则需要为它定义宽度和高度

你也可以使用线性渐变和图像: http://codepen.io/anon/pen/RPweox

.background{
  background: linear-gradient(rgba(0,0,0,.5), rgba(0,0,0,.5)),
    url('http://www.imageurl.com');
}

这是因为线性梯度函数创建的图像被添加到背景堆栈中。https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient

这里有一个更简单的技巧,只有css。

<div class="background"> </div> <style> .background { position:relative; height:50px; background-color: rgba(248, 247, 216, 0.7); background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAJElEQVQYV2NctWrVfwYkEBYWxojMZ6SDAmT7QGx0K1EcRBsFAADeG/3M/HteAAAAAElFTkSuQmCC); } .background:after { content:" "; background-color:inherit; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } </style>