close
The Wayback Machine - https://web.archive.org/web/20241007074352/https://www.geeksforgeeks.org/css-variables/
Open In App

CSS Variables

Last Updated : 13 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

CSS variables, also known as custom properties, are used to store reusable values in a CSS document. Defined with two dashes (–), these variables enhance code efficiency and readability by allowing centralized updates of values such as colors and sizes. This article explores the syntax, usage, and benefits of CSS variables, illustrating their scope through practical examples to help you streamline your web design process.

Syntax:

var( --custom-name, value );

The var() function can be used to take the values of the variables in CSS.

Parameters: The variable var() accepts two parameters which are listed below:

  • –custom-name: It is a required parameter that accepts the custom property name starting with two dashes.
  • value: It is an optional parameter. It accepts a fallback value which is used when a custom property is invalid.

Working of CSS var() function

The scope of the variables in CSS can either be local or global. We can utilize the global variables in the entire document whereas the local variable can only be used inside the selector where the variable is declared, within the scope. For creating the variables with global scope, we need to declare the variable inside the :root selector, where it compares for the document’s root element. For creating the variable in the local scope, we can declare the variable inside the selector where it can be used within the scope.

CSS Variables Examples

We will understand the above concepts through the examples.

Example 1: This example illustrates the use of the var() function to declare & access the variable globally, inside the :root selector.

HTML
<!DOCTYPE html>
<html>
<head>
    <title>CSS Variables</title>
    <style>
    :root {
        --bg-color: green;
        --txt-color: white;
    }
    /* var() function used here */
    
    body {
        background-color: var(--bg-color);
    }
    
    h1 {
        color: var(--txt-color);
    }
    
    div {
        color: var(--txt-color);
    }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <div> A computer science portal for geeks </div>
</body>
</html>

Output:

CSSVariable

Example 2: This example illustrates the use of the CSS variables for declaring the variable name, instead of copying and pasting the same colors multiple times.

HTML
<!DOCTYPE html>
<html>
<head>
    <title>CSS Variables</title>
    <style>
    :root {
        --bg-color: green;
    }
    /* var() function used here */
    
    body {
        background-color: var(--bg-color);
    }
    
    h1 {
        color: var(--txt-color, white);
    }
    
    div {
        color: var(--txt-color, white);
    }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <div> A computer science portal for geeks </div>
</body>
</html>

Output:

BERJAYA

CSS variables streamline the styling process by enabling reusable values and centralized updates. By understanding their scope—global with :root or local within specific selectors—developers can create more maintainable and efficient CSS code. Integrating CSS variables into your workflow enhances both the flexibility and manageability of your web design projects.

Supported Browsers: The browser supported by CSS variables are listed below:

  • Google Chrome 49.0
  • Microsoft Edge 15.0
  • Firefox 31.0
  • Safari 9.1
  • opera 36.0


Previous Article
Next Article

Similar Reads

React.js Blueprint Variables Font variables
In this article, we will learn about the Font Variables offered by the blueprint.js library. BlueprintJS is a React-based UI toolkit for the web. It is written in Typescript. This library is very optimized and popular for building interfaces that are complex and data-dense for desktop applications that run in a modern web browser. Font Variables: T
3 min read
Less.js Variables Default Variables
LESS (Leaner Style Sheets) is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a scripting language that improves CSS and gets compi
3 min read
Less.js Variables Properties as Variables
LESS (Leaner Style Sheets) is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a scripting language that improves CSS and gets compi
3 min read
How to define colors as variables in CSS ?
In CSS, we can define custom properties (often known as CSS variables), that offers us great flexibility to define a set of rules and avoid rewriting them again and again. We can also use custom properties to define colors. Example 1: <!DOCTYPE html> <html> <head> <title> How to define colors as variables in CSS? </title
2 min read
Primer CSS Typography Variables
In this article, we will learn how to add typography variables to the website using Primer CSS. Primer CSS is a free open-source CSS framework that is built with the GitHub design system to provide support to the broad spectrum of Github websites. It creates the foundation of the basic style elements such as spacing, typography, and color. This sys
3 min read
Difference between CSS Custom Properties and Preprocessor Variables
In this article, we will learn the difference between CSS Custom properties and Preprocessor Variables. CSS Custom Properties: CSS custom properties are also referred to as CSS variables or cascading variables. These entities contain specific values that will be reused in the entire document & can be accessed using the var() function (e.g., col
3 min read
Primer CSS Variables
Primer CSS is a free open-source CSS framework built with the GitHub design system to support the broad spectrum of Github websites. It creates the foundation of the basic style elements such as spacing, typography, and color. This systematic method ensures our patterns are steady and interoperable with every other. Object-oriented CSS principles,
9 min read
Primer CSS Breakpoint Variables
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by Object-Oriented CSS principles, functional CSS, an
4 min read
Difference between CSS Variables and Preprocessor
In this article, You will learn the differences between the CSS variables (cascading variables) and CSS preprocessors. They both implement the extra capabilities into CSS in their own different ways. CSS variables and preprocessors are two different things. Both have advantages and disadvantages. The CSS preprocessor is a language that can be used
6 min read
How to use CSS variables with TailwindCSS ?
Tailwind CSS  allows users to predefined classes instead of using the pure CSS properties.  We have to install the Tailwind CSS.  Create the main CSS file (Global.css) which will look like the below code. Global.css: In the following code, the entire body is wrapped into a single selector. The entire body is selected by using class root or id root.
1 min read
Bulma Panel Variables
Bulma is an Open source CSS framework developed by Jeremy Thomas. This framework is based on the CSS Flexbox property. It is highly responsive, minimizing the use of media queries for responsive behavior. Another advantage with Bulma is that you simply need to have an understanding of HTML and CSS to implement this framework (Although knowing JavaS
5 min read
Spectre Variables - Colors
Spectre Variables Colors are used to hold a few evergreen colors like red, green yellow, blue, gray, etc. Each color has an individual specific code, we need a variable to hold that color code to use it in the future. Spectre Variable Colors use the same method in its file like text-primary variable will hold the primary color for the text. Similar
2 min read
How to unset JavaScript variables?
To know how to unset a variable we must know what are JS variables and how to declare a variable first. JavaScript variables are containers for storing data values. Variables can be declared using the 'var' keyword. Example : var x = 5; In the above code declaration, the value 5 has been assigned to the variable 'x'. The unsetting of a variable mea
3 min read
Bulma Button Variables
Bulma is a free, and open-source CSS framework based on flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design.Buttons in Bulma CSS have classic designs in different colors, sizes, and states which makes it interactive. Variable Used: $button-color: This variable is
4 min read
What are undeclared and undefined variables in JavaScript?
Undefined: It occurs when a variable has been declared but has not been assigned any value. Undefined is not a keyword. Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier using the var or const keyword. If we use 'typeof' operator to get the value of an undeclared variable, we will face the runtime
1 min read
How to set or get the config variables in Codeigniter ?
Config Class: The Config class provides means to retrieve configuration preferences. The config items in Codeigniter can be set and get in the environment. The config value $this->config can be used to get and set items in the environment. The config items are contained within an array, namely, $config. The config file is stored at "application/
2 min read
View the list of all variables in Google Chrome Console using JavaScript
All the variables in Google Chrome can be listed for the use of debugging. There are two approaches to list all variables: Method 1: Iterating through properties of the window object: The window object in JavaScript represents the current browser's window. The properties of this object can be used to find the variables of the Chrome browser. Each o
2 min read
SASS | Variables
This article includes information about how to define a variable in SASS and scope of a variable. Prerequisite: Variables in CSS Advantages of a variable: Reduces the repetition of the same thing again and again. We can perform mathematical operations over variable like +,-,/,* etc... , which makes our work lot more easier. Declaration of a variabl
4 min read
ES6 | Variables
A variable is a named container in the memory, that stores the values. In simple words, we can say that a variable is a container for values in Javascript. The ES6 Variable names are called identifiers. The rules to keep in mind while naming an identifier. An identifier can contain alphabets and numbers but cannot be the keyword namesIt cannot star
4 min read
SASS | Use variables across multiple files
To use variables across multiple files in SASS is carried out by @import rule of SASS. @import rule which import Sass and CSS stylesheets for providing variables, @mixins and functions.Such that combine all stylesheets together for compiled css. It also imports URL such as frameworks like Bootstrap etc.. The @import no longer encouraged in future u
3 min read
How to use JavaScript variables in jQuery selectors ?
In this article, we will discuss how to use JavaScript variables in jQuery selectors. In the following examples, it can be seen that we have used the values stored in JavaScript Variables used inside the jQuery Selectors. Example 1: The concatenation technique can be applied in order to use the values stored in JavaScript variables. In the followin
2 min read
How to use Sass Variables with CSS3 Media Queries ?
SASS Variables: SASS Variables are very simple to understand and use. SASS Variables assign a value to a name that begins with $ sign, and then just refer to that name instead of the value. Despite this, they are one of the most useful tools SASS provides. SASS Variables provide the following features: Reduce repetitionDo complex mathematicsConfigu
3 min read
Reference and Copy Variables in JavaScript
In this article, we will talk about pass-by-value and pass-by-reference in JavaScript. JavaScript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the data. JavaScript has 5 primitive data types that are passed by value, they are Boolean, NULL, undefined, String, and Number. It has 3 non-primiti
5 min read
NODE_ENV Variables and How to Use Them ?
Introduction: NODE_ENV variables are environment variables that are made popularized by the express framework. The value of this type of variable can be set dynamically depending on the environment(i.e., development/production) the program is running on. The NODE_ENV works like a flag which indicates whether the server is running on development or
2 min read
Environment Variables in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. We have already discussed Command Line Arguments i
7 min read
How to watch service variables ?
$scope acts as a built-in object in AngularJs. It consists of application data and methods. The $scope is acts as a link between a controller and view (HTML). $scope is used to transfer the data. $watch: Scope in AngularJs object has $watch event which comes into picture when the model property gets changed or altered. When a data binding is create
4 min read
Setting up environment variables in Node.js in a platform independent way
Environment variables are a good way to ensure security of your precious API keys and secret stuff as well as adaptive code. However, setting up environment variables might be a bit tedious when working on various machines having different Operating Systems. At such times, a portable and project-specific way is needed to use them. Here is a way to
3 min read
What are environment variables in development ?
Environment variables is a widely used term, but what does it actually mean and why does it even exist ? Technical Definition: An environment variable is a dynamically set value that is used throughout program and determines properties of a program on each device. They are part of the environment in which a program executes. For example, a program
3 min read
How to define scope in the context of variables in LESS ?
Variable scope is used to specify the availability of variables in certain parts of the code. Firstly, the variables are searched from the local scope (i.e the variables which are declared within the code block of a particular selector); if they are not found, then they are searched from the parent scope by the compiler. Let's create an index.html
1 min read
Reading Environment Variables From Node.js
Environment Variable: The two fundamental concepts of any programming language are variables and constants. As we know that constants and variables both represent the unique memory locations that contain data the program uses in its calculations. The variable which exists outside your code is a part of your server environment and can help you by bo
2 min read