如何在 HTML 元素的背景图像中反转颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23428133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to invert colors in background image of a HTML element?
提问by Surender Thakran
I have the following div
:
我有以下几点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>
Now, I need to invert the colors of the background image to make it appear like:
现在,我需要反转背景图像的颜色,使其看起来像:
I tried using
我尝试使用
filter: invert(100%);
-webkit-filter: invert(100%);
filter: invert(100%);
-webkit-filter: invert(100%);
but it inverts the whole div
including the border making it look like:
但它反转了div
包括边界在内的整体,使其看起来像:
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.
注意:以上div
是程序生成的。反转边框颜色的解决方案也需要我更改程序以反转边框的颜色,该颜色可以是任何格式(十六进制、rgb、rgba、hsl、hsla、文字等),基本上使我膨胀代码。但是,如果我没有其他选择,那么我会这样做,但首先我希望我能找到一个更简单的解决方案。
回答by vals
You can set the background in a pseudo element, and keep the border in the div.
您可以在伪元素中设置背景,并将边框保留在 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;
}
div:after {
content: "";
position: absolute;
width: 100%;
height: 100%;
background-color:black;
background-image:url(http://i.stack.imgur.com/xQi3T.png);
background-position: -21px -35px;
background-repeat:repeat;
filter: invert(100%);
-webkit-filter: invert(100%);
}
<div></div>