如何在 CSS 中向网站添加非标准字体?
非标准字体是指 CSS 中大多数浏览器默认字体集以外的任何字体。默认字体(包括 Arial、Times New Roman 和 Verdana)是标准字体,因为它们已预装在大多数计算机和设备上。
非标准字体是指未预装的字体,必须专门加载到网站上才能使用。这些字体可以从 Google、Adobe 或 MyFonts 等网站获取。它们也可以定制设计或购买。
使用非标准字体有助于为网站设计增添独特而个性化的风格。它们通常用于创建特定外观或树立品牌的视觉形象。
在 CSS 中为网站添加一些非标准字体
在网站设计中,字体排版在打造美观度方面起着至关重要的作用。CSS 中默认的字体,例如 Arial、Times New Roman 和 Verdana,虽然功能实用,但往往显得平淡无奇。
@font-face 规则可以指定字体文件和属性,从而将字体应用于页面上的特定元素。
语法
使用 @font-face 规则的语法如下:
@font-face { font-family: 'MyFont'; src: url('path/to/MyFont.ttf') format('truetype'); font-weight: normal; font-style: normal; }
在此示例中,我们将字体系列指定为"MyFont",这是在整个 CSS 中引用字体时使用的名称。"src"属性指定字体文件的位置,"format"属性指定字体的文件格式。为了更好地兼容浏览器,建议包含多种字体格式,例如 truetype、woff、woff2、eot 等。
使用 @font-face 规则定义字体后,它会通过"font-family"属性应用于页面上的特定元素。在以下示例中,我们将自定义字体"MyFont"应用于"body"元素 -
body {
font-family: 'MyFont', Fallback, sans-serif;
}
示例
<html>
<head>
<style>
body {
background-color:pink;
}
@font-face {
font-family: 'MyFont';
src: url('/css/font/SansationLight.woff')
format('truetype');
font-weight: normal;
font-style: normal;
}
p {
font-family: 'MyFont', Fallback, sans-serif;
}
.div {
font-family: 'MyFont', Arial, sans-serif;
}
</Style>
</head>
<body>
<div class="div">This is the example of font face with CSS3.</div>
<p><b>Original Text :</b>This is the example of font face with CSS.</p>
</body>
</html>
我们还可以使用@import从远程源(例如Google Fonts或任何其他字体托管服务)导入字体。
@import url('https://fonts.googleapis.com/css?family=Permanent+Marker&display=swap');
示例
<!DOCTYPE html>
<html>
<title>Google fonts example</title>
<head>
<link href="https://fonts.googleapis.com/css?family=Permanent+Marker&display=swap" rel="stylesheet"/>
<style>
body {
font-family: "Permanent Marker";
font-size: 15px;
}
</style>
</head>
<body>
<h1>Google fonts example</h1>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Debitis non a quos repudiandae doloribus cumque! Ex rem rerum aut maiore. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Debitis non a quos repudiandae doloribus cumque! Ex rem rerum aut maiores</p>
</body>
</html>
结论
通过以上步骤,我们已成功将非标准字体添加到网站。请记住,务必确保字体文件托管在服务器上,并且浏览器可以访问,以确保字体能够正确呈现。
相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

