All You Need To Know About CSS Variables and Modifying in JavaScript

MD M Nauman Saturday, 6 October 2018 0 comments
Hello, Friends, we are writing today's article on CSS variables. The best thing about it is we can shorten our code and follow the DRY (Don't Repeat Yourself), Model. We can separate our code in parts like we do in javascript. We will cover many things just see the list below:

  1. The Syntax
  2. How to use variables values in CSS 
  3. How to access them using JavaScript
  4. How to modify them using JavaScript
  5. Why and When to use them?

The Syntax: 

 We cannot declare variables anywhere or directly. Variables should be declared within a CSS selector like in HTML, body, class, id etc but if you declare variables in any particular selector like in class or id then you can use it in its scope, not outside it.

Example: If a variable is declared inside a nav then it will be only available for the nav children not outside the nav. 

To get the global scope all you need to do is declare the variables in the root of the document. I mean you have to use the :root pseudo-class and inside it declare all your variables after doing this you can access it anywhere from the document.

To Declare globally this is the syntax:

CSS Variables

Now we know the syntax its time how to use them in our stylesheet means how to implement the custom variables values in real CSS properties.

We just saw the example above which is not working now its time to see the working example.

How to use variables values in CSS:

We have to use the built-in CSS method var() and inside it, we have to add our custom variable. 

The var() method accepts two parameters. 


var(Name_of_the_variable, Value_of_the_variable);
Name_of_the_variable The first parameter is Required it should include two dashes in the prefix
Value_of_the_variable The Second parameter is Optional Here you can assign any value as the default. it will be used if the variable value is invalid or absent.

Now I will show you the working example. Here we will use all the things which we have learned above.

Firstly we will create a variable with global scope.
:root{
--theme-color: red;
--theme-margin: 5px;
--center-me: 0 auto;
}
Here I have declared a few variables on the root element. which means I can use it anywhere on the page.

The variables which we are using from the top is theme colour, margins, and centring the element with predefined margins.


See the Pen CSS Variables by MD M Nauman (@mmnauman) on CodePen.

How to access them using JavaScript?

Here are few ways to interact with CSS variables with JavaScript you can set, remove or modify them accordingly.

Here is an example showing how to change CSS variable.



So in the above example, we have shown you how we use Javascript to change the color variable. we just need to pick the colour and the variable will get dynamically updated. We are giving you a few important ways from which you can get variables or set variables in CSS

Getting a variable from the stylesheet using Javascript.

window.getComputedStyle(container).getPropertyValue("--theme-color");

Here we have used window getComputedStyle method to get the CSS properties. Here we have used the container variable from the above example of codepen. 

You can open the example in the codepen add this above code in the console you will get the value of the variable on picking the colour.

Changing the variable value with Javascript


<strong>Choose Color: </strong>
<input type="color" value='red' id='colorPick'>
<div class='container1'></div>
<script>                let container = document.querySelector('.container1');
        let colorPick = document.querySelector('#colorPick');
        colorPick.addEventListener('change', changeColor);
        colorPick.addEventListener('mouseover', changeColor);
        function changeColor() {
            container.style.setProperty(`--theme-color`, this.value);
        }
    </script>
We are using the second codepen example to demonstrate how we can change the value of the variable using the setProperty method that is highlighted above in green color.

Now the million dollar question 

Why to use CSS variables?

  1. Like I said in the first paragraph Stylesheet for the big sites are very headache to manage as it contains 100's of lines of code. 
  2. The developers repeat their code so to avoid that we need to use CSS Variable. 
  3. We can set a theme color or theme font variables with this just changing one variable value whole site color changes. Here also we are following DRY method (Don't Repeat Yourself).
  4. We can set variables like standard, medium etc for the padding and margins. 
  5. CSS variables can be easily changes using Javascript so you can add interactivity without compromising speed.
  6. It also have scoping so you can create local and global scope variables.

When To Use CSS variables?

  1. CSS variables can be used when you think the code is getting longer and you need something to store the values so that you can use it to refer them.
  2. It can be also used to create your own standard way of coding like we use frameworks. This is built in CSS so this is very fast compare to frameworks.
  3. If you want to change sites color, margins dynamically using Javascript then you can use css variables.

Compatibility issues with cross browsers?

Image/information Source: https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables#Browser_compatibility

According to developer.mozilla.org CSS variables are not at all compatible with Internet Explorer so if you think your apps or sites users use Inter explorer then you have to rethink before using this variables.

Conclusion:

Now we know the synatx, its importance, how to use them, why to use them and when to use them. 

Now after getting so much information now your work is to practice and make sure you use them in your daily coding projects to get used to of them.

That's It Thanks For Following our Tutorial ''All You Need To Know About CSS Variables and Modifying in JavaScript'' Along With us If you found any difficulty Please Comment and Share Your Valuable Opinion. And Stay tuned for More Tutorials Like This and Share this with your friends.
Labels:

Sharing is Caring:

Next
This is the most recent post.
Previous
Older Post

0 Comments to All You Need To Know About CSS Variables and Modifying in JavaScript Post Yours! Read Comment Policy ▼