Is it possible to change text color based on background color using CSS? Is it possible to change text color based on background color using CSS? jquery jquery

Is it possible to change text color based on background color using CSS?


Here is my solution (thinking it through a different way):

Use a DIV with overflow: hidden; for the navy 'bar' that shows the rating scale.You then write out two sets of TEXT:

  1. Inside the DIV bar (overflow: hidden;), it would be white (on top)
  2. In the underlying DIV container, it would be black. (container)

The result would be an overlap of the two colored text divs:

 ________________________________|          1          |    2     ||_(dark blue w white)_|__________|<div style="position: relative; width: 250px; background: white; border: 1px solid #000; color: #000;"><div style="position: absolute; z-index: 10; overflow: hidden; width: 105px; background-color: navy; white-space:nowrap; color: #FFF;">    Between 4:00 and 6:00 blah blah</div>    Between 4:00 and 6:00 blah blah</div>

It works great because it will 'cut through' letters if the bar is at that width. Check it out, I think its what you are looking for.


Yes that's possible.

You can tie a background and a foreground color together into a class and use that on your text. So you got for example one style class having black text white background and one having white text and black background. You can switch that class then and the text will change with the background color.

And you can use jQuery('body').css('color', '#fff') for example to change the color of the body text to white.

If you provide some sample code it would even be possible to create a more specific answer for your question.


No, you can't do it with just CSS. You need JavaScript for this.

With jQuery/JavaScript you can check if an element has a CSS rule applied to it, and then do what you want, i.e.

if ( $('#element').css('white-space') == 'nowrap' ) {     // do something} else {     // do something else}

Also read here: Jquery: How to check if the element has certain css class/style