使用 CSS 中百分比和 em 的組合


我們可以結合使用百分比和 em 來指定元素的字型大小,以實現更好的字型相容性。這使我們可以在不同的瀏覽器中獲得統一的文字。百分比和 em 都是相對測量值。

語法

CSS font-size 屬性的語法如下。對於 value,以下適用於百分比和 em 單位。此外,還可以設定其他長度單位 -

Selector {
   font-size: /*value*/
}

示例

以下示例說明如何設定 CSS font-size 屬性。首先,我們使用 font-size 屬性使用百分比設定 <body> 字型 -

body {
   font-size: 80%;
}

使用 em 單位設定 <p> 元素的字型大小 -

p {
   font-size: 2em;
}

讓我們看看示例 -

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         font-size: 80%;
      }
      p {
         font-size: 2em;
      }
      span {
         font-size: 4em;
         font-style: italic;
      }
   </style>
</head>
<body>
   <p>Reading <span>source code</span> written by others gives you opportunity to criticize the mistakes done in writing that code</p>
</body>
</html>

示例

以下示例說明如何設定 CSS font-size 屬性。首先,我們使用

使用 font-size 屬性使用百分比設定字型 -

div {
   font-size: 120%;
}

設定字型大小

元素使用 em 單位 -

p {
   font-size: 2em;
}

讓我們看看示例 -

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         font-size: 120%;
      }
      p {
         font-size: 2em;
      }
   </style>
</head>
<body>
   <h3>Demo Heading</h3>
   This is example text.
   <div>
      Examples are easier to understand with practical implementation
      <p>This is another text just to display different ways to set font size in CSS.</p>
   </div>
</body>
</html>

更新於: 2024 年 1 月 2 日

297 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.