Table of Contents
管理颜色
Stackoverflow Question
Home Web Front-end CSS Tutorial First contact with CSS variables

First contact with CSS variables

Sep 11, 2018 pm 05:32 PM
css variables

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 id="管理颜色">管理颜色</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 id="Stackoverflow-nbsp-Question">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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Demystifying Screen Readers: Accessible Forms & Best Practices Demystifying Screen Readers: Accessible Forms & Best Practices Mar 08, 2025 am 09:45 AM

This is the 3rd post in a small series we did on form accessibility. If you missed the second post, check out "Managing User Focus with :focus-visible". In

Create a JavaScript Contact Form With the Smart Forms Framework Create a JavaScript Contact Form With the Smart Forms Framework Mar 07, 2025 am 11:33 AM

This tutorial demonstrates creating professional-looking JavaScript forms using the Smart Forms framework (note: no longer available). While the framework itself is unavailable, the principles and techniques remain relevant for other form builders.

Adding Box Shadows to WordPress Blocks and Elements Adding Box Shadows to WordPress Blocks and Elements Mar 09, 2025 pm 12:53 PM

The CSS box-shadow and outline properties gained theme.json support in WordPress 6.1. Let&#039;s look at a few examples of how it works in real themes, and what options we have to apply these styles to WordPress blocks and elements.

Working With GraphQL Caching Working With GraphQL Caching Mar 19, 2025 am 09:36 AM

If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

Making Your First Custom Svelte Transition Making Your First Custom Svelte Transition Mar 15, 2025 am 11:08 AM

The Svelte transition API provides a way to animate components when they enter or leave the document, including custom Svelte transitions.

Comparing the 5 Best PHP Form Builders (And 3 Free Scripts) Comparing the 5 Best PHP Form Builders (And 3 Free Scripts) Mar 04, 2025 am 10:22 AM

This article explores the top PHP form builder scripts available on Envato Market, comparing their features, flexibility, and design. Before diving into specific options, let's understand what a PHP form builder is and why you'd use one. A PHP form

Show, Don't Tell Show, Don't Tell Mar 16, 2025 am 11:49 AM

How much time do you spend designing the content presentation for your websites? When you write a new blog post or create a new page, are you thinking about

What the Heck Are npm Commands? What the Heck Are npm Commands? Mar 15, 2025 am 11:36 AM

npm commands run various tasks for you, either as a one-off or a continuously running process for things like starting a server or compiling code.

See all articles