← 第 1 关 – 建造者

第 7/12 课 ⏱ 25 分钟

字体和 class

给网站选合适的字体,并学习 class——CSS 里最有用的技巧。

跟我看:更好看的字体

浏览器默认字体很无聊。用一条规则给整个页面换字体:

body {
  font-family: Verdana, Arial, sans-serif;
}

font-family 是一个愿望清单:“用 Verdana。没有?那就 Arial。也没有?那就任何 sans-serif 字体(sans-serif)。”

几乎每台电脑都有的字体:VerdanaGeorgia(有小脚,适合较长文字)、Trebuchet MSCourier New(像打字机)。多试几种——换字体对网站效果很大。

跟我看:class

到目前为止你可以一次给 所有 段落加样式。但如果有一个段落需要看起来不同——比如重要通知呢?这就是 class 的用途:

在 HTML 里,给标签一个 class 名字:

<p class="notice">No school tomorrow!</p>

在 CSS 里,用点来选中它:

.notice {
  background-color: #fef3c7;
  border: 2px solid #f59e0b;
  padding: 10px;
  border-radius: 8px;
}

你可以给任意多个元素加同一个 class——它们都会穿一样的”衣服”。像校服,但是给标签穿的。

轮到你了 💪

  1. body 上的 font-family 给整个网站设置字体。
  2. 想一个符合你项目的 class,在两个地方使用它。
🏫 学校网站——参考答案("news" class)
<p class="news">📢 No school on Friday – teacher training day!</p>
<p class="news">📢 Paper drive starts Monday.</p>
body {
  font-family: Verdana, Arial, sans-serif;
}

.news {
  background-color: #fef3c7;
  border: 2px solid #f59e0b;
  padding: 10px;
  border-radius: 8px;
}
🙋 个人网站——参考答案("favorite" class)
<p class="favorite">⭐ Favorite game: Minecraft</p>
<p class="favorite">⭐ Favorite food: pancakes</p>
body {
  font-family: "Trebuchet MS", Verdana, sans-serif;
}

.favorite {
  background-color: #ffedd5;
  border: 2px solid #ea580c;
  padding: 10px;
  border-radius: 8px;
}
🌍 旅行日记——参考答案("tip" class)
<p class="tip">🎒 Trip tip: head up the mountain early, before it gets hot.</p>
<p class="tip">🎒 Tip: bring water shoes to the beach!</p>
body {
  font-family: Georgia, "Times New Roman", serif;
}

.tip {
  background-color: #dcfce7;
  border: 2px solid #16a34a;
  padding: 10px;
  border-radius: 8px;
}
⚽ 俱乐部网站——参考答案("win" class)
<li class="win">Eagles – Hawks 3 : 1</li>
<li>Falcons – Eagles 2 : 2</li>
<li class="win">Eagles – Wildcats 4 : 0</li>
body {
  font-family: Verdana, Arial, sans-serif;
}

.win {
  background-color: #dcfce7;
  font-weight: bold;
}

胜利马上用绿色高亮——就像真正的积分榜!

检查一下: 你的网站有了新字体,至少有一个元素用了自己的 class,看起来和别的不一样。

这堂课你要记住