字体排版主题设置
本课属于 Coddy HTML 学习旅程的“前端实践”单元。第 15 课,共 35 课。
排版是主题和设计的重要组成部分。与其到处编写字体样式,不如将它们定义为 CSS 变量,并在整个网站中重复使用。这样可以保持样式一致,也便于以后修改。
你可以为以下内容定义变量:
- 字体系列(例如,
--font-family-base、--font-family-heading)
- 字体大小(例如,
--font-size-base、--font-size-h1) - 行高
- 字符间距
首先,我们在 :root 元素中定义排版变量:
:root {
--font-primary: 'Open Sans', sans-serif;
--font-secondary: 'Roboto', sans-serif;
--font-size-base: 16px;
--line-height: 1.5;
--heading-color: #333;
--text-color: #555;
}现在,将这些变量应用到文本元素中:
body {
font-family: var(--font-primary);
font-size: var(--font-size-base);
line-height: var(--line-height);
color: var(--text-color);
}
h1, h2, h3, h4, h5, h6 {
font-family: var(--font-secondary);
color: var(--heading-color);
}这种设置创建了一个统一的排版系统,你只需在一处更改变量的值,就能轻松修改它。
挑战
简单为博客网站创建一个排版主题,分别为标题和段落文本设置变量。你的任务:
- 定义 CSS 变量,用于设置:
- 标题的字号(
--h1-size和--h2-size) - 段落文本的颜色 (
--text-color):选择一种非纯黑色,以提高可读性 - 标题文本的颜色 (
--heading-color):选择一种与正文颜色有明显区别的颜色
- 标题的字号(
- 应用这些变量来设置以下内容的样式:
- 正文文本
- h1 和 h2 标题
你的 CSS 应能让标题和段落文本呈现清晰的视觉层次。
亲手试试
<!DOCTYPE html>
<html>
<head>
<title>Typography Theming</title>
<style>
:root {
/* Typography variables */
--primary-font: "Georgia", serif; /* for paragraphs */
--secondary-font: "Arial", sans-serif; /* for headings */
}
body {
font-family: var(--primary-font);
color: #000000;
line-height: 1.6;
margin: 0;
padding: 20px;
background-color: #f9f9f9;
}
h1, h2 {
font-family: var(--secondary-font);
color: #000000;
margin-bottom: 0.5em;
}
h1 {
font-size: 16px;
}
h2 {
font-size: 16px;
}
p {
margin-bottom: 1.2em;
}
.blog-post {
max-width: 700px;
margin: 0 auto;
background: #fff;
padding: 2rem;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<div class="blog-post">
<h1>The Beauty of Typography in Web Design</h1>
<p>Typography plays a crucial role in how users read and experience content online. A good choice of fonts and sizes can make a website more readable and enjoyable.</p>
<h2>Why Typography Matters</h2>
<p>Clear and consistent typography improves accessibility, creates a visual hierarchy, and gives your website a professional feel. Without it, even the best design can look unpolished.</p>
<h2>Mobile-First Typography</h2>
<p>Starting with smaller, readable text for mobile and scaling up for desktops ensures your content looks great on any device. This approach is part of mobile-first design and theming.</p>
</div>
</body>
</html>
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
前端实践中的所有课
自己练习: Web 在线编辑器