27

I have a background of a field. The bottom is green, the top is gray. There is text on top of the background. Is there a way for the text to "sense" what color the background is and to tint the font in a way to make it contrast?

For example, the the text over the gray sky would become brighter and the text over the green field would become darker, to make it more visible.

I may be reaching pretty far on this one, but any suggestions are appreciated. (Please note, I am not looking for the answer to manually change the font colors.)

Nathan Arthur
  • 8,287
  • 7
  • 55
  • 80
Evorlor
  • 7,263
  • 17
  • 70
  • 141
  • 1
    [Methods for Contrasting Text Against Backgrounds](https://css-tricks.com/methods-contrasting-text-backgrounds) By Ana Tudor, 2017 – vsync Oct 14 '20 at 19:59
  • 1
    2023 status: `color-contrast()` looks like it will eventually provide a robust method for doing this: [Spec](https://w3c.github.io/csswg-drafts/css-color-6/#colorcontrast) | [More Examples](https://www.lambdatest.com/blog/css-color-contrast/) – Tim M. Apr 15 '23 at 16:22

1 Answers1

35

More as an experiment than otherwise:

Set the text with a background inherit, to get the background of the base; then clip it to the text, and then apply some filters to it:

.test {
    width: 800x;
    height:220px;
    font-size: 200px;
    background-image: url(bosque.jpg); 
    color: white;
    position: relative;
}

.inner {
    position: relative;
    background-image: inherit;
    -webkit-background-clip: text;
    color: transparent;
    -webkit-filter: invert() sepia();
}

fiddle

(Only working in webkit)

Check also this ones:

animated madness

contrast animation

UPDATE: We have new ways to handle this. See a demo using mix-blend-mode: difference

div {
  font-size: 300px;
  color: gray;
  mix-blend-mode: difference;
}
body {
  background-image: url(http://placekitten.com/900/600);
}
<div>TEST</div>
Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
vals
  • 61,425
  • 11
  • 89
  • 138
  • 1
    Careful! [`mix-blend-mode` isn't well-supported yet.](http://caniuse.com/#feat=css-mixblendmode) – Nathan Arthur Feb 20 '17 at 21:21
  • 7
    Apr 2020, it's now supported in everything except IE and Opera Mini (though Safari and Safari Mini have partial; no support for `hue`, `saturation`, `color` and `luminosity`). – Bing Apr 15 '20 at 23:21
  • 1
    but what if the `
    ` itself hosts both the random `background-color` **and** text `color`... `mix-blend-mode` doesn't work (i would expect it to)
    – vsync Oct 15 '20 at 11:24
  • The above doesn't work in Firefox 88. But it does in Chrome 89. – mmm111mmm Apr 01 '21 at 11:53