如何使用 CSS 更改字体大小?

cssweb developmentfront end technology更新于 2025/3/8 8:12:17

CSS,即层叠样式表,是控制网页视觉呈现的强大工具。其中之一就是能够调整页面上文本元素的字体大小。这可以通过使用 font-size 属性来实现。

要为特定元素设置特定的字体大小,我们需要结合使用类或 ID 选择器和 font-size 属性。

在本文中,我们将看到多个使用 CSS 更改字体大小的示例 -

通过使用 font-size 属性,我们可以为特定元素或类设置特定的字体大小。例如,要将元素的字体大小设置为 18 像素,我们将使用以下代码 -

P{
   font-size:18px;
}

示例

<html>
<head>
   <title>How to change the font size using CSS</title>
   <style>
      .p1{
         font-size:20px;
      }
   </style>
</head>
<body>
   <h1>Welcome to tutorialspoint</h1>
   <p class="p1">Change the font size using CSS</p>
   <p>This is normal paragraph</p> 
</body>
</html>

我们还可以使用 font-size 属性设置相对字体大小,例如更大或更小,这将根据父元素的字体大小改变字体大小。为此,我们将使用以下代码 -

P{
   font-size:larger;
}

示例

<html>
<head>
   <title>How to change the font size using CSS</title>
   <style>
      .p1{
         font-size:large;
      }
      .p2{
         font-size:small;
      }
   </style>
</head>
<body>
   <h1>Welcome to tutorialspoint</h1>
   <p class="p1">Change the font size using CSS - Large font</p>
   <p class="p2">Change the font size using CSS - Small font</p>
   <p>This is normal paragraph</p>
</body>
</html> 

另一种定位特定词语的方法是使用 :not css 选择器。这可以定位元素中除唯一词之外的所有词语。例如 -

CSS

p span:not(.unique) {
   font-size: 18px;
} 

HTML

<p>This is a <span class="not-unique">not unique</span> word, but this <span class="not-unique">word</span> is <span class="unique">unique</span>.</p> 

示例

<html>
   <head>
      <title>How to change the font size using CSS</title>
      <style>
         p span:not(.unique) {
            font-size: 20px; 
         }
      </style>
   </head>
   <body>
      <p>Lorem Ipsum is simply dummy text of <span class="notunique">not unique</span> the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, <span class="not-unique">not unique</span> when an unknown printer took a galley of type and scrambledg,</p>
   </body>
</html>

CSS 中的 font-size 属性允许精确控制网页上文本元素的大小。无论我们是想为特定元素设置特定的字体大小,还是根据父元素的字体大小调整字体大小,亦或是针对特定的单词进行调整,CSS 都能提供必要的工具来实现。


相关文章


有用资源