1

Is it possible to transform a phrase to plural using just CSS, based on the number within the element?

I'm guessing this breaks a presentation/data separation boundary philosophy, but just wondering if it's possible. It's easy with JavaScript, but wondering if CSS can take care of it.

<span class="plural">0 book</span>

outputs: 0 books

<span class="plural">1 book</span>

outputs: 1 book

<span class="plural">2 book</span>

outputs: 2 books

Scimonster
  • 32,893
  • 9
  • 77
  • 89
Dave Sumter
  • 2,926
  • 1
  • 21
  • 29

2 Answers2

9

No. CSS cannot read the content of the element to determine what number it is, and CSS doesn't have if conditions.

If you would only apply .plural to items that should be regularly pluralized, you could do:

.plural:after {content: "s"}

But then we run into the problem of how English is irregular, and not all plurals are guaranteed to end in "s".

Scimonster
  • 32,893
  • 9
  • 77
  • 89
  • thanks, I think you are right. I can only do it using a workaround by changing the plural class name on each object based on the number. – Dave Sumter Oct 27 '14 at 09:42
  • We may also run into the problem that there are over 6,000 other languages, with very interesting ways of forming and using plural. Using any simple method here guarantees that the software is seriously non-localizable. You should *generate* the HTML document with correct content, using well-structured code that has a routine for generating phrases, rather than a wired-in way of just appending a suffix. – Jukka K. Korpela Oct 27 '14 at 14:11
1

Going to try answer this myself, as it seems a pure CSS solution is not possible. I've found a small workaround here that works for me. It's not ideal, but may work for others too..

I just render the number behind the plural class name and wrap this around the s. Then I use a class for plural1 that hides the s.

This works for me because I use templates to render my html and it's easy to slot the numbers in.

.plural1 {
  display: none;
}
<div>-1 book<span class="plural-1">s</span> 
</div>

<div>0 book<span class="plural0">s</span> 
</div>

<div>1 book<span class="plural1">s</span> 
</div>

<div>2 book<span class="plural2">s</span> 
</div>

Pros: This can work for other endings and other languages too. Negative numbers are supported.

Cons: Adds unused classes to your elements (plural2, plural3, etc.) that the browser will need to read and ignore. Not really an issue for a small number of object though (eg. 100).

Dave Sumter
  • 2,926
  • 1
  • 21
  • 29
  • If you're rendering special class names, then you might as well render the suffixes themselves and drop the CSS altogether. – Stefan Dragnev Jul 26 '16 at 08:40