css pseudoclass for negative numbers

let’s say i have an html table of financial data that looks like this:

dogs 500
cats -600
fish 100
aligators 50

i would like to specify that negative numbers have the declaration {color: red} without having to individually specify style for some table cells and not others.

the code for this might look like:

TD:negative-number {color:red}

and the resulting table would look like:

dogs 500
cats -600
fish 100
aligators 50

update 16-July-2004:

the problem is that variations in content are infinite. so it probably wouldn’t make sense to create a “:negative-number” pseudoclass because 100 different people would probably request 100 different selectors for their special cases.

maybe there is a way to take advantage of simple pattern matching based on content, perhaps using regular expressions?

the following would read “make the text inside TDs red if that text begins with a hypen (minus-sign) and ends with one or more other characters.”

TD:content-regex(/^-.+/) {color:red;}

the benefit of this approach being that if negative numbers in your document are surrounded by parentheses, you can modify the regular expression in the stylesheet rather than having to modify your document to play nice with a UA’s implementation of “:negative-number”.

update 17-July-2004:

i discovered thanks to the folks on www-style that you can apply multiple classes to an element using a space separated list:

<TD CLASS="financial negative">-190</TD>

also, there is a :contains pseudoclass in the works for css3 that would definitely accomplish what i was proposing using regular expressions above. also helpful would be an NR tag in XHTML2 for specifying numbers, perhaps with attributes like positive and negative.



Yes, I like the second approach much better


I am trying to get your code above to work…but I need it to work in a form input field. I have tried

input:content-regex(/-.+/) {color:red;}

but no joy….any ideas…

Durell, content-regex does not exist in CSS, it was just something I proposed, so no browser that I know of would understand that—not that I’ve tried.

The regex doesn’t do what you intend. It will also match “blah-blah” because you haven’t constrained the – to the beginning of the match. You probably mean /^-.+/.

I think I’ve done something like what you want here.

Scott, thanks for the link. This just proves the old adage,

If you post it, they will come.

Xaprb, thanks for the regex pointer and enlightening use of CSS attribute selectors, I’ve updated the post. For everyone else, it used to read: /-.+/


Email (optional)

Blog (optional)