Home > Web Front-end > CSS Tutorial > First contact with CSS variables

First contact with CSS variables

青灯夜游
Release: 2018-09-11 17:32:15
Original
2168 people have browsed it

I believe that everyone who has just come into contact with CSS variables must have many questions about CSS variables, so let’s talk about CSS variables for you. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

How to define and use CSS variables

Start with the language we are most familiar with, JavaScript: defining variables in JavaScript uses vars.

To declare a simple JavaScript var, look like this:

var mainColor = 'red';
Copy after login

To declare a CSS variable, you must add a double dash before the name of the var. For example:

body{
    --color:red;
}
Copy after login

Now, in order to use the value of a CSS variable, we can use the var(...) function. As follows:

.demo{
    background:var(--color);
}
Copy after login

The easiest way to manage CSS variables is to declare them as: root pseudo-class. Given that CSS variables follow rules, just like any other CSS definition, placing them in :root will ensure that all selectors have access to these variables.

:root{    --color:red;
}           
.demo{
    background:var(--color);
}           
p{
    color:var(--color);
}
Copy after login

Does the browser support CSS variables?

The browser’s support for CSS variables is pretty good. It's just that IE browser doesn't support it. If you want to check browser compatibility, click here and you will see that all major browsers support CSS variables out of the box. Be it mobile or desktop.

A practical application of CSS variables

Example 1 - Managing colors

So far, One of the best candidates for using CSS variables is to manage the colors of a web page. Instead of copying and pasting the same colors over and over again, we can put them in variables. If someone asks us to update a specific shade of green or make all buttons red instead of blue, then just change the value of that CSS variable and that's it. You don't have to search and replace all instances of that color.

For example:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>管理颜色</title>
		<style type="text/css">
			/*css_vars.css*/
			:root {
			  --primary-color: #ed6564;
			  --accent-color: #388287;
			}
			
			html {
			  background-color: var(--primary-color);
			}
			
			h3 {
			  border-bottom: 2px solid var(--primary-color);
			}
			
			button {
			  color: var(--accent-color);
			  border: 1px solid var(--accent-color);
			}
			
			p {
			  color: var(--accent-color);
			}
			
			
			/*base.css*/
			* {
			  margin: 0;
			  padding: 0;
			  box-sizing: border-box;
			}
			
			html {
			  padding: 30px;
			  font: normal 13px/1.5 sans-serif;
			  color: #546567;
			  background-color: var(--primary-color);
			}
			
			.container {
			  background: #fff;
			  padding: 20px;
			}
			
			h3 {
			  padding-bottom: 10px;
			  margin-bottom: 15px;
			}
			
			p {
			  background-color: #fff;
			  margin: 15px 0;
			}
			
			button {
			  margin:0 5px;
			  font-size: 13px;
			  padding: 8px 12px;
			  background-color: #fff;
			  border-radius: 3px;
			  box-shadow: none;
			  text-transform: uppercase;
			  font-weight: bold;
			  cursor: pointer;
			  opacity: 0.8;
			  outline: 0;
			}
			
			button:hover {
			  opacity: 1;
			}
			
			.center {
			  text-align: center;
			}
		</style>
	</head>

	<body>
		<div class="container">
		  <h3>管理颜色</h3>
		  <p>管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色管理颜色</p>
		  <div class="center">
		    <button>查看详情</button><button>取消</button>
		  </div>
		</div>
	</body>

</html>
Copy after login

Rendering:

First contact with CSS variables

##Example 2 - Delete duplicate code

Typically, you'll want to build a few different variations of a component. Same basic style, slightly different. Let's use some buttons with different colors. The typical solution is to create a base class such as .btn and add variant classes.

.btn { border: 2px solid black;}
.btn:hover {background: black;}
.btn.red {border-color: red}
.btn.red:hover {background: red}
Copy after login

Now use them like this:


<button class="btn">Hello</button>
<button class="btn red">Hello</button>
Copy after login

However, this will add some code duplication. On the .red variant, we have to set the border-color and background to red.

This situation can be easily fixed using CSS variables. As follows:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>删除重复的代码</title>
		<style type="text/css">
			.btn{
			  border-radius:4px;
			  text-align:center;
			  padding:.5em;
			  margin-bottom:0.5em;
			  background:#fff;
			  border:1px solid var(--color, black);
			}
			.btn:hover{
			  color:#fff;
			  cursor:pointer;
			  background:var(--color, black);
			}
			.btn.red{
			  --color:red;
			}
			.btn.green{
			  --color:green;
			}
			
			.btn.blue{
			  --color:blue;
			}
		</style>
	</head>

	<body>
		<div class="btn">HMOE</div>
		<div class="btn red">HMOE</div>
		<div class="btn green">HMOE</div>
		<div class="btn blue">HMOE</div>
	</body>

</html>
Copy after login

Rendering:

First contact with CSS variables

Example 3 - Make some attributes readable

If we want To create shortcuts to more complex property values, CSS vars are great to use so we don't have to remember it. CSS properties like box-shadow, transform and font or other CSS rules that take multiple parameters are perfect examples. We can put the property in a variable so that we can reuse it in a more readable format.

Example:

:root {
  --tiny-shadow: 4px 4px 2px 0 rgba(0, 0, 0, 0.8);
  --animate-right: translateX(20px);
}

li {
  box-shadow: var(--tiny-shadow);
}

li:hover {
  transform: var(--animate-right);
}
Copy after login

Example 4 - Cascading Variables

Standard cascading rules also apply to CSS variables. So if a custom property is declared multiple times, the lowest definition in the css file will override the definitions above it. The following example demonstrates how easy it is to dynamically manipulate properties of user actions while still keeping the code clear and concise.

CSS_var.css file:

.orange-container {
  --main-text: 18px;
}
.orange-container:hover {
  --main-text: 22px;
}
.red-container:hover {
  --main-text: 26px;
}
.title {
  font-size: var(--title-text);
}
.content {
  font-size: var(--main-text);
}.container:hover {
  --main-text: 18px;
}
Copy after login

base.css file:


* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}html {
  background: #eee;
  padding: 30px;
  font: 500 14px sans-serif;
  color: #333;
  line-height: 1.5;
}.orange-container {
  background: orange;
}.red-container {
  background: red;
}.red-container,
.orange-container {
  padding-top: 10px;
  padding-left: 50px;
}.container {
  background: blue;
  padding: 20px;
  color: white;
}p {
  transition: 0.4s;
}.title {
  font-weight: bold;
}
Copy after login

index.html file:

<html>

<head>
<link rel="stylesheet" type="text/css" href="base.css">
<link rel="stylesheet" type="text/css" href="css_vars.css">
</head>

<body>
<div class="orange-container">
    Hover orange to make blue bigger.
    <div class="red-container">
         Hover red to make blue even bigger.
        <div class="container">
            <p class="content">Hover on the different color areas to change the size of this text and the title.</p>
        </div>
    </div>
</div>
</body>

</html>
Copy after login

Rendering:

First contact with CSS variables

Example 5 - Theme Switcher with CSS Variables

One benefit of CSS variables is its reactivity. Once we update it, any properties with CSS variable values ​​will also be updated. So, with just a few lines of Javascript and smart use of CSS variables, we can make a theme switcher mechanism.

For example:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>具有CSS变量的主题切换器</title>    
        <style>
            
            body {
              background-color: var(--bg, #b3e5fc);
              color: var(--bg-text, #37474f);
              font-family: sans-serif;
              line-height: 1.3;
            }
            
            .toolbar {
              text-align: center;
            }
            
        </style>
    </head>
    <body>
        
        <div class="toolbar">
            <button value="dark">dark</button>
            <button value="calm">calm</button>
            <button value="light">light</button>
        </div>
    
        <h2>Stackoverflow Question</h2>
        <p>I would like to use an external javascript file in another javascript file. For example, I could store all my global variables
        in a globals.js file and then call then from the website logic logic.js. Then in the index.html, i would insert the tag.
        How do I use the globals.js inside the logic.js?
        </p>
        <script>
            var root = document.documentElement;
            var themeBtns = document.querySelectorAll(".toolbar > button");
            
            themeBtns.forEach(function (btn){
              btn.addEventListener("click", handleThemeUpdate);
            });
            
            function handleThemeUpdate(e) {
              switch (e.target.value) {
                case "dark":
                  root.style.setProperty("--bg", "black");
                  root.style.setProperty("--bg-text", "white");
                  break;
                case "calm":
                  root.style.setProperty("--bg", "#B3E5FC");
                  root.style.setProperty("--bg-text", "#37474F");
                  break;
                case "light":
                  root.style.setProperty("--bg", "white");
                  root.style.setProperty("--bg-text", "black");
                  break;
              }
            }
        </script>

    </body>
</html>
Copy after login

Rendering 1--just run:

First contact with CSS variables## Rendering 2--click dark:

5First contact with CSS variables Rendering 3--Click calm:

## Rendering 4--Click light: 5First contact with CSS variables

5First contact with CSS variables

CSS变量的使用提示

像CSS中几乎所有的东西一样,变量也非常简单易用。以下是一些未包含在示例中的提示,但在某些情况下仍然非常有用:

1)css变量区分大小写。下面的示例是两个不同的变量:

:root {
   --color: blue;
   --COLOR: red;
}
Copy after login

2)当您使用var()函数时,您可以使用第二个参数。如果找不到自定义属性,将使用第二个参数为默认值:

width: var(--custom-width, 50%);
Copy after login

3)可以直接将CSS变量用于HTML:

<!--HTML--><html style="--size: 600px"><!--CSS-->body {
  max-width: var(--size)
}
Copy after login

4) 可以在其他CSS var中使用CSS变量:

--base-red-color: #f00;
--background-gradient: linear-gradient(to top, var(--base-red-color), #222);
Copy after login

5) 可以使用媒体查询使CSS变量成为条件。例如,以下代码根据屏幕大小更改填充的值:

:root {
    --padding: 15px 
}@media screen and (min-width: 750px) {
    --padding: 30px}
Copy after login

6) 不要害怕在 clac() 函数中使用CSS变量。

--text-input-width: 5000px;
max-width: calc(var(--text-input-width) / 2);
Copy after login

当然,CSS变量不是灵丹妙药。不会解决你在CSS领域遇到的每一个问题。但是,使用它使您的代码更具可读性和可维护性。此外,它极大地改善了大型文档的易变性。只需将所有常量设置在一个单独的文件中,当您只想对变量进行更改时,就不必跳过数千行代码。

The above is the detailed content of First contact with CSS variables. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template