使用 CSS 变量
本课属于 Coddy HTML 学习旅程的“前端实践”单元。第 2 课,共 35 课。
CSS 变量也称为自定义属性,你可以用名称保存值,并在 CSS 中重复使用它们。
变量在选择器内声明(通常使用 :root,这样变量就能在页面的任何位置生效,这称为全局),语法如下:
:root {
--main-color: midnightblue;
--padding: 16px;
}要使用存储在变量中的值,请使用 var() 函数:
.button {
background-color: var(--main-color);
padding: var(--padding);
}挑战
简单你有一个网页,展示了几部正在电影院上映的电影。每部电影都有一个购买电影票按钮。
你的任务:
- 在
:root选择器中创建一个名为--main-color的 CSS 变量,并将其值设为seagreen。 - 使用这个变量设置页面上所有
<button>元素的背景颜色。
亲手试试
<html>
<head>
<title>How to declare a variable</title>
<style>
:root {
--bg-color: #4c87f5;
/* Write CSS rules here */
}
body {
font-family: Arial, sans-serif;
background: var(--bg-color);
padding: 20px;
}
.movie {
background: white;
padding: 15px;
margin-bottom: 15px;
border-radius: 8px;
}
.movie h2 {
margin: 0 0 10px;
}
.movie p {
margin: 0 0 10px;
}
button {
color: black;
border: none;
padding: 8px 12px;
border-radius: 4px;
cursor: pointer;
/* Write CSS rules here */
}
</style>
</head>
<body>
<h1>Today's Movies</h1>
<div class="movie">
<h2>Ocean Whispers</h2>
<p>A sailor discovers a hidden island and the secrets of the sea.</p>
<button>Buy Ticket</button>
</div>
<div class="movie">
<h2>Midnight Chase</h2>
<p>A detective races against the clock to stop a mysterious heist.</p>
<button>Buy Ticket</button>
</div>
<div class="movie">
<h2>Starlight Bakery</h2>
<p>A warm comedy about friendship and following your dreams.</p>
<button>Buy Ticket</button>
</div>
</body>
</html>
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
前端实践中的所有课
自己练习: Web 在线编辑器