CSS 使用 font-weigh 根据粗细程度选择不同的字体

技巧9个月前 隔壁老李于 2023-08-17 07:32:39 最后编辑

看到这个标题,有人第一反应可能是 font-weigh 不就是是控制字体粗细的吗?为什么要选择不同字体包?

因为很多字体不包含粗细级别,设置 font-weight 是无效的!

我们来看下面这个例子

使用同一个字体,font-weight 分别设置为 600、500、400、300

@font-face {
    font-family: B;
    src: url('A.ttf');
}
.f {
    font-family: 'B';
}
<ul>
  <li class="f" style="font-weight: 600;">600隔壁老李</li>
  <li class="f" style="font-weight: 500;">500隔壁老李</li>
  <li class="f" style="font-weight: 400;">400隔壁老李</li>
  <li class="f" style="font-weight: 300;">300隔壁老李</li>
</ul>

结果我们看到的字体粗细是一样的

CSS 使用 font-weigh 根据粗细程度选择不同的字体  第1张

接下来来点不一样的

我们通过 @font-face 中的 font-weight 属性来设置不同的粗细使用不同的字体包

@font-face {
    font-family: A;
    src: url('A-B.ttf');
    font-weight: 600;
}
@font-face {
    font-family: A;
    src: url('A-M.ttf');
    font-weight: 500;
}
@font-face {
    font-family: A;
    src: url('A-R.ttf');
    font-weight: 400;
}
@font-face {
    font-family: A;
    src: url('A-L.ttf');
    font-weight: 300;
}
.ff {
    font-family: 'A';
}

解释:把一个字体,名为 A,当 font-weight 为 600 的时候,使用 A-B.ttf 字体,为 500 的时候,使用 A-M.ttf 字体,为 400 的时候,使用 A-R.ttf 字体,为 300 的时候,使用 A-L.ttf 字体。

我们应用如下HTML代码

<ul>
  <li class="ff" style="font-weight: 600;">600隔壁老李</li>
  <li class="ff" style="font-weight: 500;">500隔壁老李</li>
  <li class="ff" style="font-weight: 400;">400隔壁老李</li>
  <li class="ff" style="font-weight: 300;">300隔壁老李</li>
</ul>

不同的粗细效果出现了

CSS 使用 font-weigh 根据粗细程度选择不同的字体  第2张

使用这种方式,我们可以为不同的 font-weight 选择不同的字体,使网页设计的更加精致!

本文由 @隔壁老李 于 2023-08-16 发布在 野路子博客,如无特别说明,本博文章均为原创,转载请保留出处。
评论 (0)
访客
Top