在CSS中,可以使用自定义属性(也称为CSS变量)来定义和重用值。这使得样式更加灵活和易于维护。自定义属性以--开头,后面跟着变量的名称和值。

定义变量

要定义一个CSS变量,你可以在:root伪类选择器中或者在任何其他选择器内部使用它,如下所示:

:root {
  --main-color: #3498db;
  --font-size: 16px;
}

在这个例子中,我们定义了两个变量:--main-color 和 --font-size。这些变量可以在整个文档中使用。

使用变量

要使用一个变量,你可以在属性值中使用var()函数,并传入变量的名称,如下所示:

body {
  background-color: var(--main-color);
  font-size: var(--font-size);
}

示例

以下是一个完整的示例,展示了如何在HTML文档中使用CSS变量:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Variables Example</title>
<style>
  :root {
    --main-bg-color: #f3f3f3;
    --text-color: #333;
    --link-color: #007bff;
  }
  body {
    background-color: var(--main-bg-color);
    color: var(--text-color);
    font-family: Arial, sans-serif;
  }
  a {
    color: var(--link-color);
    text-decoration: none;
  }
  a:hover {
    text-decoration: underline;
  }
</style>
</head>
<body>
  <h1>Welcome to the CSS Variables Example</h1>
  <p>This is an example of using <a href="#">CSS variables</a>.</p>
</body>
</html>

在这个示例中,我们定义了三个变量(--main-bg-color--text-color, 和 --link-color),并在bodya元素中使用这些变量来设置背景颜色、文本颜色和链接颜色。这使得样式更加集中和可维护。如果你需要改变主题颜色,你只需在:root选择器中更新变量的值即可