css中使用变量,可以将它们放在变量中,而不必一遍又一遍地复制和粘贴相同的颜色

示例子:
在这里插入图片描述
在这里插入图片描述

CSS 变量
var() 函数用于插入 CSS 变量的值。

CSS 变量可以访问 DOM,这意味着您可以创建具有局部或全局范围的变量,使用 JavaScript 来修改变量,以及基于媒体查询来修改变量。

使用 CSS 变量的一种好方法涉及设计的颜色。您可以将它们放在变量中,而不必一遍又一遍地复制和粘贴相同的颜色

在这里插入图片描述

1.传统方式的css代码:

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-color: #1e90ff;
}

h2 {
  border-bottom: 2px solid #1e90ff;
}

.container {
  color: #1e90ff;
  background-color: #ffffff;
  padding: 15px;
}

button {
  background-color: #ffffff;
  color: #1e90ff;
  border: 1px solid #1e90ff;
  padding: 5px;
}
</style>
</head>
<body>

<h1>传统方式</h1>

<div class="container">
  <h2>Welcome to Shanghai!</h2>
  <p>Shanghai is one of the four direct-administered municipalities of the People's Republic of China.</p>
  <p>Shanghai is one of the four direct-administered municipalities of the People's Republic of China.</p>
  <p>
    <button>Yes</button>
    <button>No</button>
  </p>
</div>

</body>
</html>

2.使用var变量的css代码:

<!DOCTYPE html>
<html>
<head>
<style>
:root {
  --blue: #1e90ff;
  --white: #ffffff; 
}

body {
  background-color: var(--blue);
}

h2 {
  border-bottom: 2px solid var(--blue);
}

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}
</style>
</head>
<body>

<h1>使用 var() 函数</h1>

<div class="container">
  <h2>Welcome to Shanghai!</h2>
  <p>Shanghai is one of the four direct-administered municipalities of the People's Republic of China.</p>
  <p>Shanghai is one of the four direct-administered municipalities of the People's Republic of China.</p>
  <p>
    <button>Yes</button>
    <button>No</button>
  </p>
</div>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_46409887/article/details/114684579