htmlcssbackground-blend-mode

Blend mode with parent DIV


The standard way to blend an image with a colour is to use the following CSS:

background-image: url(photo.jpg);
background-color: red;
background-blend-mode: multiply;

I want to do this without using CSS to specify the photo, because the IMG is already being generated by the PHP of a Wordpress theme, which I don't want to mess with.

Is there a way of applying a blend mode to an IMG so that it blends with its parent DIV (or any element higher up the hierarchy)? That way I could use CSS to apply the blend mode to the IMG and a background colour to its parent DIV. (I can't seem to apply a background colour directly to an IMG).

Thanks! I hope that makes sense.


Solution

  • you need to put the img inside a div, like this:

    <div class="container">
        <img src="img.png" />
    </div>
    

    And apply following styles to the parent div: (I'm using 250x100 as image size)

    width: 250px;
    height: 100px;
    background-color: red;
    

    And the following styles to the img: (Need to have to same width and height like above)

    width: 25px;
    height: 100px;
    mix-blend-mode: multiply;
    

    So you're mix-blending the background-color of the parent div with the img which is inside the parent div. Should look like this:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    
        <style>
            .container {
                width: 250px;
                height: 100px;
                background-color: red;
            }
    
            .container img {
                width: 250px;
                height: 100px;
                mix-blend-mode: multiply;
            }
        </style>
    </head>
    <body>
    <div class="container">
        <img src="https://images.unsplash.com/photo-1633113089631-6456cccaadad?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80" />
    </div>
    </body>
    </html>