A preliminary understanding of CSS custom properties

A preliminary understanding of CSS custom properties

Today, CSS preprocessors are the standard for web development. One of the main benefits of preprocessors is that they enable you to use variables, which helps you avoid copying and pasting code and simplifies development and refactoring.

In this article, you’ll learn how to integrate CSS variables into your CSS development workflow, which can make your stylesheets more maintainable and less repetitive.

Now, let me get started!

1* CSS variable syntax

<1> What are CSS variables?

If you have used any programming language, you should already be familiar with the concept of variables. Variables allow you to store and update values ​​that your program needs in order to work.

The benefits of using variables in CSS are not too different from the benefits of using variables in programming languages.

Here's what the spec says about it:

[Using CSS variables] makes it easier to read large files, as seemingly-arbitrary values ​​now have informative names, and makes editing such files much easier and less error-prone, as one only has to change the value once, in the custom property, and the change will propagate to all uses of that variable automatically.

W3C Specification .

[Using CSS variables] makes it easier to read large files, because seemingly arbitrary values ​​now have informative names, and makes editing such files easier and less error-prone, because a value only needs to be changed once in a custom property, and that change will automatically propagate to all places the variable is used.

<2>css custom variable syntax

To declare a variable instead of a common CSS property (like color or fill), simply provide a custom named property starting with -:

.box{
  --box-color: #4d4e53;
  --box-padding: 0 10px;
}

The value of a property can be any valid CSS value: a color, a string, a layout value, or even an expression.

Here are some useful custom properties:

:root{
  --main-color: #4d4e53;
  --main-bg: rgb(255, 255, 255);
  --logo-border-color: rebeccapurple;
  --header-height: 68px;
  --content-padding: 10px 20px;
  --base-line-height: 1.428571429;
  --transition-duration: .35s;
  --external-link: "external link";
  --margin-top: calc(2vh + 20px);
  /* Valid CSS custom properties can be reused later in, say, JavaScript. */
  --foo: if(x > 5) this.width = 10;
}

If you're not sure about :root, in HTML it's the same as html but with a higher specificity, the equivalent of a global variable.

<3> Use of CSS variables

var() Function

To use CSS variables, you use the var() CSS function, passing the CSS variable name to the function:

.box{
  --box-color:#4d4e53;
  --box-padding: 0 10px;

  padding: var(--box-padding);
}

.box div{
  color: var(--box-color);
}

The syntax of the var() function is:

var( <custom-property-name> [, <declaration-value> ]? )

The first argument to the method is the name of the custom attribute to replace. The optional second argument to the function is used as a fallback value. If the first argument refers to an invalid custom property, the function uses the second value.

You can do this if you are not sure whether a custom property has been defined and want to provide a value to use as a fallback.

For example:

color: var(--foo, red, blue); //Specify both red and blue as fallback values; that is, any value between the first comma and the end of the function will be considered a fallback value.

padding: var(--box-padding, var(--main-padding));

calc() Function

As we are used to working with preprocessors and other languages, we expect to be able to use basic operators when working with variables. For this purpose, CSS provides a calc() function, which causes the browser to recalculate the expression after any changes to the value of a custom property:

:root{
  --indent-size: 10px;

  --indent-xl: calc(2*var(--indent-size));
  --indent-l: calc(var(--indent-size) + 2px);
  --indent-s: calc(var(--indent-size) - 2px);
  --indent-xs: calc(var(--indent-size)/2);
}

If you are trying to work with unitless values, using the calc() function can be very convenient:

:root{
  --spacer: 10;
}
.box{
  padding: var(--spacer)px 0; /* DOESN'T work */
  padding: calc(var(--spacer)*1px) 0; /* WORKS */
}

CSS custom property scope

Custom properties also obey the CSS cascade rules.

2* Use CSS custom attributes with JS

Suppose you have a CSS variable called --left-pos with a value of 100px, scoped to the .sidebar class in your CSS document:

.sidebar {
--left-pos: 100px;
}

You can get the value of --left-pos as follows:

const sidebarElement = document.querySelector('.sidebar');
const cssStyles = getComputedStyle(sidebarElement);
const cssVal = String(cssStyles.getPropertyValue('--left-pos')).trim();
console.log(cssVal); //100px

Set the CSS property value:

sidebarElement.style.setProperty('--left-pos', '200px');

3* What is the difference between css variables and preprocessor variables?

When styling your website, you probably take advantage of the flexibility of variables by using preprocessors like Sass and Less.

The preprocessor allows you to set variables, and use them in functions, loops, mathematical operations, etc. Does this mean that CSS variables don't matter?

Not exactly, mainly because CSS variables are different from preprocessor variables.

The difference stems from the fact that CSS variables are real CSS properties that work in the browser, whereas preprocessor variables need to be compiled into regular CSS code, so the browser knows nothing about them.

This means you can update CSS variables, inline style attributes and SVG presentation properties within your stylesheet document, or choose to manipulate them dynamically using JavaScript. Modifications to CSS custom properties will be immediately passed to the place where they are used, but preprocessors cannot accomplish this because they are compiled in advance!

That’s not to say you need to choose between one or the other: there’s nothing stopping you from taking advantage of the superpowers of CSS and preprocessor variables working together.

Summarize

The above is my introduction to CSS custom properties. I hope it will be helpful to you. If you have any questions, please leave me a message and I will reply to you in time. I would also like to thank everyone for their support of the 123WORDPRESS.COM website!

<<:  Learn how to use the supervisor watchdog in 3 minutes

>>:  In-depth explanation of hidden fields, a new feature of MySQL 8.0

Recommend

Vue+element ui realizes anchor positioning

This article example shares the specific code of ...

Linux Dig command usage

Dig Introduction: Dig is a tool that queries DNS ...

A brief discussion on MySQL temporary tables and derived tables

About derived tables When the main query contains...

Detailed steps to install VMware Tools from scratch (graphic tutorial)

VMware Tools is a tool that comes with VMware vir...

Shorten the page rendering time to make the page run faster

How to shorten the page rendering time on the bro...

Vue large screen display adaptation method

This article example shares the specific code for...

Mybatis implements SQL query interception and modification details

Preface One of the functions of an interceptor is...

Mysql classic high-level/command line operation (quick) (recommended)

Since I need to learn how to build servers and da...

How to view server hardware information in Linux

Hi, everyone; today is Double 12, have you done a...

Three.js realizes Facebook Metaverse 3D dynamic logo effect

Table of contents background What is the Metavers...

Example code of layim integrating right-click menu in JavaScript

Table of contents 1. Effect Demonstration 2. Impl...

Let's talk about the Vue life cycle in detail

Table of contents Preface 1. Life cycle in Vue2 I...

How to configure VMware multi-node environment

This tutorial uses CentOS 7 64-bit. Allocate 2GB ...

A brief discussion on React Component life cycle functions

What are the lifecycle functions of React compone...

Use iptables and firewalld tools to manage Linux firewall connection rules

Firewall A firewall is a set of rules. When a pac...