10

I have a grid of different shades of blue, they each contain text, I need the text to be white if the background is dark and vice versa, I have:

color: #333;
isolation: isolate;
mix-blend-mode: difference;

but that somehow changes the background colour of the elements to some wierd orangy grey. Is there a CSS-only (less-only) option that will invert the text colour only?

2

2 Answers 2

11

You could also apply this styling to the element you'd like to invert the colors of:

filter: invert(1);
mix-blend-mode: difference;

It especially works if you need to base the difference on a child or a element further away, not a parent or a close element.

I used it with a custom cursor (the black circle), which made it contrast nicely with the elements behind. Sample pen here: https://codepen.io/m3t4lch7/pen/VwwOKNd

Cursor with inverted colors

8

You can set the text color to transparent, and use background-clip and filter to invert and grayscale the color displayed through the transparent text.

Check out a more detailed explanation of the various effects you can achieve this way at Methods for Contrasting Text Against Backgrounds.

In your case, it sounds like you are looking for something like the following:

#one {
  background-color: blue;
}

#two {
  background-color: white;
}

span {
  background: inherit;
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  filter: invert(1) grayscale(1);
  -webkit-filter: invert(1) grayscale(1);
}
<div id="one">
  <span>Some text</span>
</div>
<div id="two">
  <span>Some text</span>
</div>

8
  • Thank you for your response, however this is not quite the result I was looking for, I. the effect makes the actual text invisible, I would like the text to have the inverse colour.
    – J-Cake
    Jun 23, 2018 at 4:01
  • Probably a browser specific issue. Edited the answer for improved browser support after testing on Chrome and Firefox (also removed contrast from filter as it seems to have little effect in some browsers, but know that experimenting with the filter values including chaining additional filters may enable a better rendering of the text color, contrast, etc).
    – benvc
    Jun 23, 2018 at 16:20
  • I use Chrome Canary. I also tried it in IE and Edge. But thank you.
    – J-Cake
    Jun 24, 2018 at 0:13
  • Tested in Chrome, Firefox and Edge and it works for me. Maybe there is some conflicting css on the site you are testing.
    – benvc
    Jul 14, 2018 at 15:46
  • 1
    there probably is, if it worked for you, then I don't see why it shouldn't work. thanks for trying.
    – J-Cake
    Jul 15, 2018 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.