深色和浅色模式基础
本课属于 Coddy HTML 学习旅程的“前端实践”单元。第 13 课,共 35 课。
深色/浅色模式是一项很受欢迎的功能,用户可以选择自己喜欢的配色方案。让我们使用 CSS 变量来实现一个基本的深色/浅色模式切换功能。
首先,在根元素中定义浅色模式的颜色变量,并将它们应用于不同的元素:
:root {
--background-color: #ffffff;
--text-color: #333333;
--heading-color: #000000;
}
body {
background-color: var(--background-color);
color: var(--text-color);
}
h1, h2, h3 {
color: var(--heading-color);
}接下来,创建一个暗色模式类,用来覆盖这些变量:
.dark-mode {
--background-color: #333333;
--text-color: #f5f5f5;
--heading-color: #ffffff;
}现在,.dark-mode 类控制主题。将这个类添加到 <body> 后,变量会发生变化,所有使用这些变量的元素都会自动更新。
<body class="dark-mode">
<!-- 在这里填写你的页面内容 -->
</body>要动态切换模式,我们需要借助另一种语言 JavaScript (JS) 来添加或移除 .dark-mode 类。在这节课中,你可以通过在 <body> 标签上添加或移除这个类来手动测试。
挑战
简单你的任务:
- 在
<style>部分中添加一个.dark-mode类。 - 覆盖 CSS 变量,为背景、文本、标题和按钮设置深色。
- 将
class="dark-mode"添加到<body>标签中进行测试。
亲手试试
<!DOCTYPE html>
<html>
<head>
<title>Dark/Light Mode Basics</title>
<style>
/* Default light theme */
:root {
--background-color: #f0f4f8;
--text-color: #222222;
--heading-color: #003366;
--button-bg: #ffcc00;
--button-text: #000000;
}
body {
background-color: var(--background-color);
color: var(--text-color);
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: var(--heading-color);
color: white;
padding: 2rem;
text-align: center;
}
header h1 {
margin: 0;
font-size: 2rem;
}
main {
padding: 2rem;
}
h2 {
color: var(--heading-color);
margin-top: 1.5rem;
}
p {
line-height: 1.6;
}
.button {
display: inline-block;
margin-top: 1rem;
padding: 0.75rem 1.5rem;
background-color: var(--button-bg);
color: var(--button-text);
border: none;
border-radius: 5px;
text-decoration: none;
font-weight: bold;
cursor: pointer;
}
footer {
background-color: var(--heading-color);
color: white;
text-align: center;
padding: 1rem;
margin-top: 2rem;
}
</style>
</head>
<body>
<header>
<h1>Olympic Games 2025</h1>
<p>Celebrating sports, unity, and excellence</p>
</header>
<main>
<h2>Top Sports</h2>
<p>From track and field to swimming and gymnastics, the Olympics showcase the best athletes in the world.</p>
<a href="#" class="button">See Medal Winners</a>
<h2>Host Cities</h2>
<p>Explore the exciting host cities where athletes come together to compete at the highest level.</p>
<a href="#" class="button">Learn More</a>
<h2>History</h2>
<p>The Olympic Games have a rich history dating back to ancient Greece, promoting peace, friendship, and fair competition.</p>
</main>
<footer>
© 2025 Olympic Games. All rights reserved.
</footer>
</body>
</html>
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
前端实践中的所有课
自己练习: Web 在线编辑器