Surender Thakran
Surender Thakran

Reputation: 4054

How to invert colors in background image of a HTML element?

I have the following div:

<div style="border-radius:50%; height:233px; width:423px; background-color:black; background-image:url(image2.gif);background-repeat:repeat; border:solid  1px; filter: invert(100%);-webkit-filter: invert(100%);"></div>

enter image description here

Now, I need to invert the colors of the background image to make it appear like: enter image description here

I tried using

filter: invert(100%); -webkit-filter: invert(100%);

but it inverts the whole div including the border making it look like: enter image description here

How can I invert the colors of only the background image as opposed to that of the whole element?

Note: The above div is programmatically generated. The solution to invert the color of the border as well will need me to change the program to invert the color of the border, which may be in any format (hex, rgb, rgba, hsl, hsla, words etc), essentially bloating my code. However if no other option is available to me then I would do it but first I am hoping I can find a simpler solution.

Upvotes: 21

Views: 71827

Answers (1)

vals
vals

Reputation: 64174

You can set the background in a pseudo element, and keep the border in the div.

This way the filter will not affect the main element

div {
    border-radius:50%;
    height:233px;
    width:423px;
    border:solid 1px green;
    overflow: hidden;
    position: relative;
    text-align: center;
    line-height: 170px;
}

div:after {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    background-color:black;
    background-image:url(https://i.sstatic.net/xQi3T.png);
    background-position: -21px -35px;
    background-repeat:repeat;
    filter: invert(100%);
    -webkit-filter: invert(100%);
    z-index: -1;
}
<div>Text long</div>

Upvotes: 26

Related Questions