背景
通过CSS属性@font-face和font-family可以实现加载自定义web font,改变网页字体,实现美化效果。
1.引用字体文件
出于版权风险考虑,尽量使用免费可商用的字体作为web font。
本文教程使用的为站酷仓耳渔阳字体,是站酷发布的免费可商用字体。
字体下载地址:https://www.zcool.com.cn/special/zcoolyytfonts
需要通过@font-face属性引用web font。
引用实例:
@font-face {font-display: swap;font-family: 'afengblogfont';src: url('https://libs.afengim.com/font/typeface/file/TsangerYuYangT/TsangerYuYangT-W03.woff2') format('woff2');url('https://libs.afengim.com/font/typeface/file/TsangerYuYangT/TsangerYuYangT-W03.woff') format('woff');url("https://libs.afengim.com/font/typeface/file/TsangerYuYangT/TsangerYuYangT-W03.eot");url("https://libs.afengim.com/font/typeface/file/TsangerYuYangT/TsangerYuYangT-W03.eot?#iefix") format('embedded-opentype'), }
属性详解:
font-display swap属性可以实现在web font未加载完成前使用浏览器默认字体渲染文本,当web font加载成功后再替换自定义字体,避免出现网页文本空白现象,影响用户阅读及体验。
font-family属性在此可以自定义web font的名称,以便在其他css样式中引用该名称,如此处使用的名称为:afengblog
src需要填写web font url,可以引用多个字体文件,但需要通过format定义该字体的格式,以便在多种浏览器中兼容,如:woff woff2 ttf
2.设置元素字体
引用完字体文件后需要通过font-family属性定义该元素的字体,如下示例:
html {font-family: "afengblogfont", sans-serif;font-weight: 400;font-style: normal; }
font-family属性填写引用字体文件设置的font-family属性名称
最终示例:
@font-face {font-display: swap;font-family: 'afengblogfont';src: url('https://libs.afengim.com/font/typeface/file/TsangerYuYangT/TsangerYuYangT-W03.woff2') format('woff2');url('https://libs.afengim.com/font/typeface/file/TsangerYuYangT/TsangerYuYangT-W03.woff') format('woff');url("https://libs.afengim.com/font/typeface/file/TsangerYuYangT/TsangerYuYangT-W03.eot");url("https://libs.afengim.com/font/typeface/file/TsangerYuYangT/TsangerYuYangT-W03.eot?#iefix") format('embedded-opentype'), }html {font-family: "afengblogfont", sans-serif;font-weight: 400;font-style: normal; }
WordPress可以添加至主题根目录style.css文件的开头或添加到 外观>自定义>额外CSS内,无需添加style标签。
原文地址:(美化)WordPress网站添加自定义字体 - 阿峰博客