Css在背景图像上应用背景

时间:2015-02-19 11:09:26

标签: css background

我目前有两张图片,我想对它们应用滤镜或渐变:

HTML:

<div class='category_a tinted'>

</div>
<div class='category_b tinted'>

</div>

的CSS:

.category_a{
  background-image : url(...);
}
.category_b{
  background-image : url(...);
}

.tinted{
  background: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5), 100%);
}

但是,它的背景会覆盖background-image属性。如何同时获得色调和图像(不重复代码)。

3 个答案:

答案 0 :(得分:2)

    background-image: url(), gradient-goes-here

试试这个。它会工作

    background-image: url(IMAGE), linear-gradient(...Color You Want...)

答案 1 :(得分:1)

要扩展@ChronixPsyc点,附加到单独类的伪元素将实现此目的。

如果div有内容,您可能会遇到z-index的问题,但这可以修复。

[class*="category"] {
    width: 100px;
    height: 100px;
    display: inline-block;
    border:1px solid red;
    margin: 25px;
}
.tinted > * {
    position: relative; /* required to 'set' z-index */
}

h2 {
    color: white;
    text-align: center;
}

.category_a {
    background-image: url(http://lorempixel.com/100/100/sports/1/);
}

.category_b {
    background-image: url(http://lorempixel.com/100/100/sports/2/);
}

.tinted {
        position: relative; /* positioning context */
}

.tinted::before {
    content:"";
    position: absolute;
    width: 100%;
    height: 100%;
    top:0;
    left:0;
    background-image: linear-gradient(to bottom, rgba(255,0,0,0.5), rgba(0,0,0,0.5));
}
<div class="category_a tinted">
    <h2>Caption</h2>>
</div>

<div class="category_b tinted">
        <h2>Caption</h2>>
</div>

答案 2 :(得分:0)

如果您使用的是LESS,请尝试以下内容:

.category_a:after {
    content:"";
    .tinted; // class with your background;
    position:absolute;
    // Add your top, bottom, left, right here
    z-index:1;
}

或者,如果您不使用LESS,请尝试此

.category_a:after {
    content:"";
    position:absolute;
    // Add your top, bottom, left, right here
    background: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), 100%);
    z-index:1;
}