為頁面上的所有數字設置字體

[英]Set a font specifically for all numbers on the page


For my webpage, I chose a font that works well for all the letters. However, for all numbers I'd like to use a different font.

在我的網頁上,我選擇了一種適合所有字母的字體。但是,對於所有的數字,我想使用不同的字體。

Is there a way that I can set a CSS rule to target all the numbers on the page?

有沒有一種方法可以設置一個CSS規則來針對頁面上的所有數字?

If I can't do it strictly with CSS, my first thought is to use regular expressions to surround all numbers with a span with a "numbers" class and apply a font for that class. Is there a better way to do this?

如果我不能嚴格地使用CSS來完成,我的第一個想法是使用正則表達式將所有數字用一個“number”類包圍起來,並為該類應用一個字體。有更好的方法嗎?

2 个解决方案

#1


16  

You can do it in JavaScript relatively simply by traversing the document so that you wrap any sequence of digits in a span element with a class attribute and declare font-family for it in CSS.

只需遍歷文檔,就可以在JavaScript中實現這一點,這樣就可以在span元素中使用類屬性包裝任何數字序列,並在CSS中聲明字體族。

It’s possible in principle in pure CSS, too, though only WebKit browsers currently support this:

雖然目前只有WebKit瀏覽器支持這一點:

@font-face {
  font-family: myArial;
  src: local("Courier New");
  unicode-range: U+30-39;
}
@font-face {
  font-family: myArial;
  src: local("Arial");
  unicode-range: U+0-2f, U+40-10FFFF;
}
body { font-family: myArial; }

Finally, and most importantly, don’t do it. If you are dissatisfied with digits in a font, don’t use that font.

最后,也是最重要的,不要這樣做。如果你對字體中的數字不滿意,不要使用那種字體。

#2


1  

Surrounding your numbers with a <span class="number"> sounds like a good, semantically sound approach.

使用 包圍您的數字聽起來是一個很好的、語義上合理的方法。

In fact, CSS3 doesn't offer an alternative, and I don't see anything forthcoming in CSS4. If you look at the latest CSS3 recommendation, it doesn't specify any content selector, but the old 2001 candidate recommendation was the last version to provide the :contains() pseudoclass.

事實上,CSS3並沒有提供替代方案,我也沒有看到CSS4會有任何進展。如果查看最新的CSS3推薦,它沒有指定任何內容選擇器,但是舊的2001候選推薦是提供:contains()贗類的最后一個版本。

This would let you match an element that contained numbers:

這將使您匹配包含數字的元素:

/* Deprecated CSS3 */
p:contains(0), p:contains("1"), p:contains("2") {
    background-color: red;
}

Even if this were actually available, it matches the p, not the number, so the whole p would be styled...not what you wanted. The CSSWG is kicking around these ideas for formatting numerical content...still not what you wanted.

即使這實際上是可用的,它與p匹配,而不是數字,所以整個p將被樣式化…不是你想要的。CSSWG正在考慮這些格式化數字內容的想法……仍然不是你想要的。

To apply CSS to the numbers, there is no avoiding some additional markup.

要將CSS應用到數字上,沒有避免一些額外的標記。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/11/28/72531df1d645624487488aaec8ecedae.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com