unicode-range 字体混搭(转)

最先想到的方法是定义两个拥有不同字体CSS类分别赋予不同的元素。

<div class="font1"></div>
<div class="font2"></div>

但是这个方法是最笨的,而且是不能完全达到要求,因为有些后端传来的字符串无法在之前就猜到时中文字符还是其他的。比如:

<div class="font_x">${news_title}</div>

所以,我参考了一些文章,发现了unicode-range这个属性,用来解决这个问题。

干货如下:

<html>
<head>
<meta charset="utf-8">
    <style type="text/css">
        @font-face {
            font-family: 'mixFont';
            src: url('fonts/STHeiti-Light.ttf');
            unicode-range: U+4E00-9FCB;/*汉字字符集*/
        } 
        @font-face {
            font-family: 'mixFont';
            src: url('fonts/HelveticaThin.ttf');
        }
        body{
            font-family:mixFont, Arial;
            font-size: 2rem;
        }
        @font-face {
            font-family: 'STHeiti';
            src: url('fonts/STHeiti-Light.ttf');
        }
        span{
            font-family: STHeiti;
        }
    </style>
</head>
<body>
    这里是一些中文字符,These are couples of characters excepect Chinese.*&(%$(^651644'Hello world' <span> 'Hello world' so as to comparetion.</span>
</body>
</html>

代码中,使用自定义字体定义了两次mixFont,第一次用unicode-range来控制了应用相应的字体(STHeiti-Light)的应用范围即U+4E00-9FCB,而这正是汉字的Unicode字符集。第二次用不同的字体(HelveticaThin)定义mixFont,而没有加unicode-range,这样会应用于汉字字符集之外的字符上。
之后,将mixFont应用到body上就可以了,这样干净利落地完成了区分字体。
接着,为了对比测试结果,又创建了一个STHeiti字体应用到span上,这样能清晰的对比字体之间的差异。



文/乘着风(简书作者)
原文链接:http://www.jianshu.com/p/7980ec695326
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
posted @ 2016-10-25 21:43  讲义大魔王  阅读(585)  评论(0编辑  收藏  举报