• Home
  • Inspiration
  • Design / Dev
  • Freebies
  • Deals
  • Home
  • Inspiration
  • Design / Dev
  • Freebies
  • Deals
CodeGrape Community Blog CodeGrape Community Blog
Input your search keywords and press Enter.
Design / Dev

CSS Variables: An Introduction, With Code Examples

by codegrape / July 26, 2020

CSS variables, also known as CSS custom properties, expand the script-like functionality of CSS into something that resembles a programming language.

If you’re at all familiar with any type of programming language, you know that variables are the foundation of any action. Variables are set, compared, altered, and saved throughout the program as the means of its functionality. And while the addition of variables to CSS hardly makes it into Swift or C++, but it’s a step in that kind of direction.

Despite leaning towards a programming language, CSS seems reluctant to give the programmer full flexibility with these variables. They’re similar to local variables within a scripting language, mostly just expanding your overall reach without fundamentally changing the language’s paradigm.

Essentially, CSS variables allow you to set a property once and then reuse it throughout your stylesheet. For example, you can have a variable called --brand_color which specifies HEX, RGB, or HSL values for your client’s branded red color. Then, you can grab that variable whenever you want that color just by referencing the variable name. If you’re unfamiliar with how variables work, you can imagine this functionality like “find and replace” in Word. Every time the CSS processor encounters a variable name, it takes the associated property from the variable declaration and replaces the variable’s name with that property. It’s essentially a shortcut to grabbing more complicated properties. If you’ve ever worked with CSS pre-processors, you’ll recognize that these are basically the variable-like functionality of pre-processors like Less and Sass imported into the main branch of the CSS language.

CSS Variables: Syntax

The variable name must begin with two hyphens (–) and is case sensitive. There aren’t any other rules about syntax, but in general, avoiding spaces is a good idea.

The following CSS rule declares a custom property of global scope named --main-color, It has a value of the HEX color code #abcdef:

:root { 
  --main-color: #abcdef; 
}

CSS Variables: Scope = Cascade

To declare a variable in CSS, you need to start by specifying the scope of the variable. Global variables apply at the root level of the DOM, while more specific variables are associated with only their attached selector. Variables with any scope follow the same cascading priority rules of the rest of CSS. Essentially, the more specific the selector, the higher-priority the associated property. Classes are more specific than element categories, which are more specific than the parent selector :root. Variables are declared within a CSS selector that defines its scope.

For global variables, there are the :root or body selector.

:root { 
  --backgroud-color: white; 
} 

body { 
  --background-color: green; 
}

These variables both have the same effective scope. The variables below, on the other hand, have an ever-narrowing scope.

:root   { --color: #abc; } 
span    { --color: 130, 10, 150; } 
.class  { --color: #123; }

When the variable is called, it returns the value you supplied when initializing the variable. As what amounts to a typing shortcut, it basically replaces its own name with the values assigned to it at runtime. This permits us to also slot in different properties in different places, but draw from a palette of settings selected at the beginning of your design. As a result, you can more easily achieve consistency across a design. And, perhaps best of all, you can effectively mass-edit properties. By changing the initialized value of the variable, you’ll change the properties applied to any of the elements with that variable. You might think of it as changing a “theme” of the design rather than a single property.

We’ve used colors so far in our examples, but CSS variables can be used to call the values for any properties, including padding, size, and other properties.

CSS Variables: Adding to Variables

You can also use the “find and replace” function of variables to include your variable’s value inside of the rest of a property declaration. For example,if you only specify the rgb channels in your rgba() color codes, you can then add the desired alpha value in context. This process is described below:

:root {
  --main-color: 240, 0, 25;
}

#foo {
  color: var(--main-color);
}

If you want to specify an alpha channel for your RGB and HSL colors only on certain elements, you can tack the alpha channel on from within the variable recall. You can see this in action below:

:root { 
  --brand_color: 240, 5, 52; 
} 

#foo { 
  color: rgba(var(--brand-color), 0.5); 
}

CSS Variables: Specifying Other Properties

Variables can take the placeholder for just about any property. For example, the following example uses variables for both color and padding.

<head> 
  :root { 
    --default-pad: .5em, 1em; --my-color: #121212; 
  } 

  .pad { 
    padding: var(--default-pad); 
  } 

  .mycolor { 
    color: var(--my-color); 
  } 
</head> 

<body> 
  <div class="pad"> 
    <h2 class="pad">same padding as parent div</h2> 
    <p class="mycolor">this text is colored by --my-color</p>
  </div>
</body>

Here, the div and h2 elements both use the same padding, while the paragraph sets the text color from a different variable.

Conclusion

CSS variables are most useful when you’re declaring a set of default properties at the top of your style sheets. They’re great for building and altering important design elements in a unified way, or for allowing users to specify certain colors without a design for interaction with HTML5 and CSS3 alone. As of publication, CSS variables are supported by all major browsers except for IE 11 (but Edge does provide support).

cascadecodecssexamplepropertyscopesyntaxvariable
  • ♥104 938
  • Read More
  • Next PostHow to Edit Text in Photoshop

Related Posts

How To Improve UX With Sketching
November 25, 2021
10 Best Quiz Maker Plugins For WordPress in 2022
March 16, 2022
Top 10 Wireframe Tools to Try for Mobile App Design
January 4, 2021

No Comments

Leave a Reply Cancel Reply

What To Think About When Growing Your Business

November 24, 2023

Continue Reading

Unraveling the Mastery of Networking on LinkedIn: Unleashing the Power of Connections

November 24, 2023

Continue Reading

Why Your Business Can’t Afford to Ignore UX Design in the Digital Age

November 2, 2023

Continue Reading

Key Factors to Consider Before Starting Your Business Journey

November 1, 2023

Continue Reading

The Impact of Graphic Design on Business Performance

October 29, 2023

Continue Reading

Newsletter

Latest Posts

  • What To Think About When Growing Your Business
    November 24, 2023
  • Unraveling the Mastery of Networking on LinkedIn: Unleashing the Power of Connections
    November 24, 2023
  • Why Your Business Can’t Afford to Ignore UX Design in the Digital Age
    November 2, 2023
Corporate Business Card https://www.codegrape.com/ Corporate Business Card
https://www.codegrape.com/item/corporate-business-card/49184

#brand #business #card #cmyk #corporate #creative #psd
Clean Minimal Corporate Flyer Design https://www.c Clean Minimal Corporate Flyer Design
https://www.codegrape.com/item/clean-minimal-corporate-flyer-design/48844

#creative #flyer #corporate #liflet #stationery
Real Estate Flyer Template https://www.codegrape.c Real Estate Flyer Template
https://www.codegrape.com/item/real-estate-flyer-template/48818

#flyer #interior #design #agency #poster #mortgage
Qtheme - Photography Website Template https://www. Qtheme - Photography Website Template
https://www.codegrape.com/item/qtheme-photography-website-template/52831

#qtheme #simple #modern #html #bootstrap #photography #website #template
Corporate Business Flyer https://www.codegrape.com Corporate Business Flyer
https://www.codegrape.com/item/corporate-business-flyer/48800

#a4 #advertisement #agency #business #flyer #corporate #creative #psd
InstaMedia - Download From Instagram https://www.c InstaMedia - Download From Instagram
https://www.codegrape.com/item/instamedia-download-from-instagram/49516

#instagram #download #social #image #video #photo #tool
Tri Fold Brochure Design https://www.codegrape.com Tri Fold Brochure Design
https://www.codegrape.com/item/tri-fold-brochure-design/48594

#trifold #brochure #design #illustrator
Corporate Business Card https://www.codegrape.com/ Corporate Business Card
https://www.codegrape.com/item/corporate-business-card/48542

#stylish #modern #business #card #corporate #creative #design #elegant #trend
Follow on Instagram
  • Scripts
  • Themes
  • Plugins
  • Prints
  • Graphics
  • Mobile Apps

Copyright © 2022 CodeGrape. All Rights Reserved.