How to apply css to only numbers in a text inside/or any <p><p> element?

17,589

Solution 1

This can be done using CSS's unicode-range property which exists within @font-face.

The numbers 0 to 9 exist in Unicode within the range U+0030 to U+0039. So what you'll need to do is include a font alongside your existing font which specifically targets this range:

@font-face { 
    font-family: 'My Pre-Existing Font';
    ...
}
@font-face {
    font-family: 'My New Font Which Handles Numbers Correctly';
    ...
    unicode-range: U+30-39;
}

The result of this will be that every instance of Unicode characters U+0030 (0) through to U+0039 (9) will be displayed in the font which specifically targets that range, and every other character will be in your current font.

Solution 2

You can wrap all numbers in p tags with a <span class="number">:

CSS

.number {
   font-family: Verdana;
}

jQuery

$('p').html(function(i, v){
    return v.replace(/(\d)/g, '<span class="number">$1</span>');
});

But personally, I would go with James suggestion ;)

http://jsfiddle.net/ZzBN9/

Solution 3

There is no way to apply CSS to all numbers specifically. In each number tag you could add the attribute class='number' and then in the CSS you could add

.number {
   font-family: arial;
}
Share:
17,589
Sinju Angajan
Author by

Sinju Angajan

Updated on July 21, 2022

Comments

  • Sinju Angajan
    Sinju Angajan almost 2 years

    I am Using a Regional language unicode font-face in my site but the numbers are not looking good.

    So I want to apply new font-style or css to numbers only..

    please help

  • MeiSign
    MeiSign over 10 years
    This is a very nice solution but you might want to implement a javascript fallback if browser doesn't support unicode-range... As far as I know its a pretty new specification.
  • Jukka K. Korpela
    Jukka K. Korpela over 10 years
    unicode-range isn’t supported by Firefox or by IE versions up to IE 8.
  • Jukka K. Korpela
    Jukka K. Korpela over 10 years
    Depending on what “number” means, you might need to add “.”, “,”, “’”, “-”, “−”, “+”, etc., and then you would have problems, since they may appear outside numbers, too. The rule given is as such OK for unsigned integers (digit sequences).
  • Sinju Angajan
    Sinju Angajan over 10 years
    @JukkaK.Korpela..Ok..Thank you..Let me try..(Y)
  • geotheory
    geotheory over 8 years
    Would it be possible to give a working demo of this? e.g. jsfiddle.net/geotheory/e0owrwne
  • Rudy Velthuis
    Rudy Velthuis about 8 years
    I know it's late, but what about return v.replace(/(\d+)/g, etc... ? That groups 12 and 1234 together into one span, instead of putting a span on each digit.
  • vinesh
    vinesh over 7 years
    @geotheory see my answer for more clarification stackoverflow.com/a/40088765/842386
  • Pourdad.Daneshmand
    Pourdad.Daneshmand about 2 years
    This code worked for me, Thanks