Stick
Stick

Reputation: 489

format a number to a character with css

I'm working with a list of numbers in a table, specifically golf scores. And I want to replace occurrences of '0' with 'E'. I was doing this at the application level but the javascript I'm currently using to do some sorting gets very confused finding a letter in the middle of all the numbers. I look at it as a presentation problem and was hoping there's a css based solution.

Upvotes: 1

Views: 524

Answers (2)

artlung
artlung

Reputation: 34013

Not really. There was an effort to allow for a :contains() selector but that got removed.

Here's a sneaky way to get the effect you want, though I suspect what you really need to do is fix the way your JavaScript executes sorts.

So what you can do is add an attribute to your list, I've called mine data-score and replicate the scores.

Then using the CSS attribute match selectors, you add some content, the "E", and alongside that you make the "E" black, and the original content ("O") white.

<style type="text/css">
ul {
    list-style-type: none;
}
/* turn the "0" white */
li[data-score="0"] {
    color: #fff;
}
/* make an E, in black */
li[data-score="0"]:before {
    content: "E";
    color: #000;
}
</style>

<ul>
    <li data-score="100">100</li>
    <li data-score="0">0</li>
    <li data-score="10">10</li>
    <li data-score="5">5</li>
    <li data-score="100">100</li>
</ul>

Which will display as:

100
E
10
5
100

With the "0" really being there, but not visible.

Read more about: :before selector, content, data attributes.

Additionally, if you just plain output the "E" for a "0", and use data attributes for the sort, you can avoid the CSS hackery I'm suggesting.

Upvotes: 1

Bojangles
Bojangles

Reputation: 101473

There isn't, unfortunately. You'll have to do it with JavaScript or on the server side.

Upvotes: 3

Related Questions