Scipion
Scipion

Reputation: 11888

Css apply background on background image

I am currently have two images and I would like to apply a filter or gradient on them :

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%);
}

However, it background overrides the background-image property. How can I have both the tint and the image (without duplicating the code).

Upvotes: 1

Views: 79

Answers (3)

Paulie_D
Paulie_D

Reputation: 115066

To expand on @ChronixPsyc point, a pseudo-element attached to a separate class would achieve this.

You may run into issues with z-index if the div has content but this can be fixed.

[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>

Upvotes: 1

ChronixPsyc
ChronixPsyc

Reputation: 476

If you're using LESS, try something like the below:

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

Or if you're not using LESS, try this

.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;
}

Upvotes: 0

Gibbs
Gibbs

Reputation: 22964

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

Try this. It ll work

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

Upvotes: 2

Related Questions