DEV Community

Marwan Ahmed
Marwan Ahmed

Posted on

Using Variables in CSS makes it easy, try to learn the basics through my post...

Think about this if a client came to you or you had a project working on it in a company, and you were required to create a website and use CSS in it, and you wrote, for example, 6000 lines of CSS code, and after you handed over the project, the client came to you and said, “This color is not the best thing for me, and we want to change it.” Is it better to make each element a color or a specific one, and then sit around this element in its selector inside CSS and try to think of what color you were using or what it was called by any naming system, whether RGB or Hex or whatever, or is it better to have a way to unite the colors In the whole site and use them as you want?
Of course, the second solution is better and faster, but how can we apply it??

  • There is something called "CSS Custom Properties", or as an abbreviation of the name we call it "CSS Variables", so how can I use it?

:root {
--paragraphs-color: #FF0000;
--p-fontSize: 1.2em;
}

P {
color: var(--paragraphs-color);
font-size: var(--p-fontSize);
}

The above code means, in short, that I define a variable named paragraphs-color that holds value, which is the color red, and I define a variable named p-fontSize that holds a value that is 1.2em, which is equal to 19.2px. I have it on the site, and I call them inside each paragraph, and this makes me forget the idea that I might forget the color that I used in the paragraphs before, and it makes it easier for me. All you have to do if you forgot is to go back to the root or the original and see from it the styles that you initialized, this applies to all You can change the elements and selectors that you have on the site to styles and call them anywhere you want...

I hope that the information will be useful to you if it is still the first time you know it, and if it is not the first time, then I hope that I have added something new to you.

Top comments (2)

Collapse
 
ataha2001 profile image
ataha2001

useful information.. Thanks

Collapse
 
marwanahmed77 profile image
Marwan Ahmed

You are welcome