CSS Variables with JavaScript

CSS Variables — The var() Function

The var() function is used to insert the value of a CSS variable.

CSS variables have access to the DOM, which means that you can create variables with local or global scope, change the variables with JavaScript, and change the variables based on media queries.

A good way to use CSS variables is when it comes to the colors of your design. Instead of copy and paste the same colors over and over again, you can place them in variables.

The Traditional Way

The following example shows the traditional way of defining some colors in a style sheet (by defining the colors to use, for each specific element):

Example

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

button background-color: #ffffff;
color: #1e90ff;
border: 1px solid #1e90ff;
padding: 5px;
>

Syntax of the var() Function

The var() function is used to insert the value of a CSS variable.

The syntax of the var() function is as follows:

Value Description
name Required. The variable name (must start with two dashes)
value Optional. The fallback value (used if the variable is not found)

Note: The variable name must begin with two dashes (—) and it is case sensitive!

How var() Works

First of all: CSS variables can have a global or local scope.

Global variables can be accessed/used through the entire document, while local variables can be used only inside the selector where it is declared.

To create a variable with global scope, declare it inside the :root selector. The :root selector matches the document’s root element.

To create a variable with local scope, declare it inside the selector that is going to use it.

The following example is equal to the example above, but here we use the var() function.

First, we declare two global variables (—blue and —white). Then, we use the var() function to insert the value of the variables later in the style sheet:

Example

.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;
>

Advantages of using var() are:

  • makes the code easier to read (more understandable)
  • makes it much easier to change the color values
Читайте также:  Show php errors in php file

To change the blue and white color to a softer blue and white, you just need to change the two variable values:

Example

.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;
>

Browser Support

The numbers in the table specify the first browser version that fully supports the var() function.

CSS var() Function

Источник

How to Use Variables in CSS and Streamline Your Styling

Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Most websites use CSS to polish their appearance and style different web page components. CSS, or Cascading Style Sheet, is not technically a programming language. However, CSS can be used with programming languages like JavaScript to create responsive and interactive web pages.

If you have used programming languages, such as JavaScript, you know that you can declare a variable, assign it a value and reuse it in various parts of your code. The good news is that you can apply the same concept in CSS.

This article will define CSS variables, describe their benefits, and show you how to declare and use a variable in CSS.

What-are-variables-in-CSS

What are Variables in CSS?

CSS variables are custom properties that allow web developers to store values they can reuse through the stylesheet. For instance, you can declare the font style, background color, and font size that you can reuse with elements such as headings, paragraphs, and divs in your codebase.

Why use CSS variables? These are some of the reasons;

  • Makes it easier to update code: Once you declare a variable, you can reuse your entire stylesheet without updating every element manually.
  • Reduces repetition: As your codebase grows, you will find that you have similar classes and elements. Instead of writing CSS code for every item, you can simply use CSS variables.
  • Makes your code more maintainable: Code maintenance is important if you want your business to be a going concern.
  • Improves readability: The modern world encourages collaboration. Using variables in CSS results in a compact codebase that is readable.
  • Easy to maintain consistency: CSS variables can help you maintain a consistent style as your source code grows or app-size increases. For instance, you can declare the margins, padding, font style, and colors to be used in your buttons across the website.

How to Declare Variables in CSS

Since you know understand what variables in CSS are and why you should use them, we can go ahead and illustrate how to declare them.

To declare a CSS variable, start with the element’s name, then write two dashes (–), the desired name and value. The basic syntax is;

Читайте также:  Php debug on centos

For instance, if you want to apply padding in your entire document, you can declare it as;

Scope of Variables in CSS

CSS variables can be scoped locally (accessible within a specific element) or globally (accessible in the entire style sheet).

Local variables

Local variables are added to specific selectors. For instance, you can add them to a button. This is an example;

The background color variable is available on the button selector and its children.

Global variables

Once declared, you can use global variables with any element in your code. We use the :root pseudo-class to declare global variables. This is how we declare them;

In the above code, you can use any of the variables declared with different elements, such as headings, paragraphs, divs, or even the entire body.

How to use Variables in CSS

We shall create a project for demonstration purposes and add index.html and styles.css files.

In the index.html file, we can have a simple div with two headings ( h1 and h2 ) and a paragraph ( p ).

 

Hello Front-end Dev.

This is how to use variables in CSS.

Keep scrolling

In the style.css file, we can have the following;

When the web page is rendered we will have the following;

screenzy-1681246689788

From the code above, we have declared global variables in the :root element. We must use the var keyword to use the global variable in any of our elements. For instance, to apply the background color we declared as a global variable, we present our code as follows;

Check all the other elements, and you will note a trend in how the var keyword is applied.

Use CSS Variables with JavaScript

We will use local and global variables to illustrate how to use CSS variables with JavaScript.

We can add an alert element to our existing code;

Our new index.html document will be as follows;

 

Hello Front-end Dev.

This is how to use variables in CSS.

Keep scrolling

We can style our variable. Add the following code to your existing CSS code;

We have done the following;

Add JavaScript code

We can make our alert element responsive; when you click it, you get a pop-up on your browser which says; “We have used CSS Variables with JavaScript. ”.

We can add JavaScript code directly to the HTML code by enclosing it using tags. JavaScript code should come after HTML code, but before closing the tag.

  

Your HTML code should now look something like this;

Screenshot-from-2023-04-11-15-19-10

Our JavaScript does the following;

  • We use document.querySelector() to locate the alert element.
  • We assign the alert element a variable alertDiv .
  • On the alertDiv, we use addEventListener() method to add a ‘click’ event.
  • We use the window.alert() to display a message when the click event happens.
Читайте также:  List in html with numbers

When the page is rendered, you will have the following;

screenzy-1681246835983

When you click the alert , you get the following;

screenzy-1681246888674

Fallback Values in CSS Variables

What happens when you reference a variable not defined in your stylesheet? The CSS effect you intend to apply will not be applied. Fallback values offer a value of an effect that will appear instead of the unreferenced variable.

Fallback values are useful in the following ways;

  • If certain browsers don’t understand CSS variables, the select property can have something to fall back to.
  • If you suspect a page is not working as expected due to a CSS variable, you can use a Fallback value to test if it is true.

You can have more than one fallback property, separated by commas. Take this code, for instance;

If you misspell the word primary-color when using the global variable, which means it is undeclared, it will pick red, the Fallback value.

We can demonstrate it better with this code;

If you render it on the browser, you get this;

screenzy-1681246957036

However, we can get the same code and change just one character on the button selector as follows;

The browser will now render this;

screenzy-1681247011055

Use Dynamic Value and Calculated Value Variables in CSS

Dynamic values are updated automatically based on certain events or conditions, such as user inputs.

     :root < --color: #333; >#color-input < margin-left: 1em; >#color-input  The above code does the following;
  • We declare a variable —color with a default value of #333 using the :root selector.
  • We use #color-input to select the input element.
  • The value of —color is set to var(—color-input) , which means the color always updates when the user picks a new color using the color picker.

Calculated values perform calculations based on other properties or variables. We can illustrate it using this code;

From this code block, we can note the following;

  • We have —base-font-size variable that defines the base font size.
  • We have —header-font-size , which is 3 times the value of –base-font-size.
  • We have a h1 selector that uses var with —header-font-size .
  • So, all the h1 in the web page will be thrice the size of —base-font-size .

Wrapping Up

You now understand how to use CSS variables to speed up the development process and write code that is easy to maintain. You can use custom variables with HTML and libraries such as React. Check out different approaches you can use to style React using CSS.

You can check the source code here.

Источник

Оцените статью