111

HTML

<div>
    <p>inverted color</p>
</div>

CSS

div {
    background-color: #f00;
}
p { 
    color: /* how to use inverted color here in relation with div background ? */
}

Is there any way to invert the p color with CSS?

There is color: transparent; why not color: invert; even in CSS3?

TylerH
  • 20,816
  • 57
  • 73
  • 92
Bhojendra Rauniyar
  • 78,842
  • 31
  • 152
  • 211
  • 2
    -webkit-filter: invert(100%); – daniel__ Jul 19 '13 at 08:42
  • 1
    This could be very helpfull to you: http://net.tutsplus.com/tutorials/html-css-techniques/say-hello-to-css3-filters/ – Ron van der Heijden Jul 19 '13 at 09:02
  • 3
    In [this fiddle](http://jsfiddle.net/g5UHM/2/) I tried to combine 3 approaches: CSS filter for WebKit, SVG filter for Firefox, and the brilliant trick with `outline-color: invert` [invented by Lea Verou](http://lea.verou.me/2011/04/invert-a-whole-webpage-with-css-only/) for IE. Unfortunately, Opera (Presto) didn't clip the area filled with outline by `overflow`, so it won't work there. I hope that this demo may still be useful for the further experiments. – Ilya Streltsyn Jul 19 '13 at 09:18
  • @Ronvander the link is dead – Nathan Kulzer Apr 01 '21 at 18:33

3 Answers3

159

Add the same color of the background to the paragraph and then invert with CSS:

div {
    background-color: #f00;
}

p { 
    color: #f00;
    -webkit-filter: invert(100%);
    filter: invert(100%);
}
<div>
    <p>inverted color</p>
</div>
TylerH
  • 20,816
  • 57
  • 73
  • 92
Bruno Lemos
  • 8,008
  • 5
  • 35
  • 49
  • 2
    This inverts the `color`, but not the `background`. It just so happens that `color` is set to the same as `background-color`. See [below](/a/58460326/579078) for a solution that inverts the backdrop. – ᅙᄉᅙ Oct 20 '19 at 20:41
29

Here is a different approach using mix-blend-mode: difference, that will actually invert whatever the background is, not just a single colour:

div {
  background-image: linear-gradient(to right, red, yellow, green, cyan, blue, violet);
}
p {
  color: white;
  mix-blend-mode: difference;
}
<div>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscit elit, sed do</p>
</div>
ᅙᄉᅙ
  • 17,132
  • 10
  • 64
  • 97
  • 5
    +1 `mix-blend-mode: difference` works where `filter: invert(100%)` fails when used with `position: fixed` (say modals) https://stackoverflow.com/a/37953806/366332 – Vanni Totaro Apr 15 '20 at 17:41
  • Doesn't work on [economist.com](https://www.economist.com/). `html {mix-blend-mode: difference !important;}` does not invert the background. (neither does `html {filter: invert(100%) !important;}`) – tejasvi88 Mar 04 '22 at 12:10
2

I think the only way to handle this is to use JavaScript

Try this Invert text color of a specific element

If you do this with css3 it's only compatible with the newest browser versions.

Community
  • 1
  • 1
Jan Peter
  • 880
  • 6
  • 17