如何在 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>

結論

透過以上步驟,我們成功地將非標準字型新增到網站。請記住,為了使字型能夠正確渲染,必須確保字型檔案託管在伺服器上並且瀏覽器可以訪問。

更新於:2023年3月9日

503 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.