@font-face 允许网页中使用自定义的字体,这些自定义的字体被放置在服务器上,从而让网页摆脱对访问者计算机上字体环境的依赖。
简单的说,有了@font-face,只需将字体上传到服务器端,无论访问者计算机上是否安装该字体,网页都能够正确的显示。
@font-face 的语法规则如下,
@font-face { font-family: <fontName>; src: <source> [<format>]; font-style: <style>; font-weight: <weight>; }
font-family 属性用来指定字体的名称 (必须)。
source 属性用来指定字体文件的存放路径,可以是相对路径或绝对路径 (必须)。
formart 属性用来指定字体的格式,支持 ttf,otf,wotf,eot,svg 等格式 (可选)。
font-style 属性用来指定字体风格,比如斜体 oblique 或 italic,默认为 normal (可选)。
font-weight 属性用来指定字体的粗细,比如 bold, 默认为 normal (可选)。
举例如下:
我要让网站使用统一字体 Cantarell,则先下载好该字体的四种版本:Regular,Bold,Oblique,BoldOblique,并将它们放在当前 css 文件的上一级目录的 font 子目录下 (即 ../font),然后在 css 文件中设置如下,
/* User Defined Font */ @font-face { font-family: 'myfont'; src: url("../font/Cantarell-Regular-gloden.otf"); } @font-face { font-family: 'myfont-bold'; src: url("../font/Cantarell-Bold-gloden.otf"); font-weight: bold; } @font-face { font-family: 'myfont-oblique'; src: url("../font/Cantarell-Oblique-golden.otf"); font-style: oblique; } @font-face { font-family: 'myfont-bold-oblique'; src: url("../font/Cantarell-BoldOblique-golden.otf"); font-weight: bold; font-style: oblique; }
使用时,可以对大部分元素设置一个公共字体,例如,
body, button, input, select, textarea { font-family: 'myfont'; }
然后对个别元素,设置其他字体,例如,
.header-box > ul.lf > li > a { /* font-weight: bolder; */ font-family: 'myfont-bold'; }
对于默认有粗体的元素,例如 h1, h2, 等,需要明确指定使用自定义粗体,例如,
h1, h2, h3, h4 { font-family: 'myfont-bold'; }
===========================================================
本文大部分内容来自于网友博客:https://blog.csdn.net/ixygj197875/article/details/79323554
@font-face 的基本语法规则可参考:https://www.runoob.com/cssref/css3-pr-font-face-rule.html