DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. CSS Variables Scoping to Create and Theme Flexible UI Components

CSS Variables Scoping to Create and Theme Flexible UI Components

This article explains how to use CSS variables and take advantage of scoping to create better UI component styles.

Sergio Carracedo user avatar by
Sergio Carracedo
·
Mar. 09, 23 · Tutorial
Like (3)
Save
Tweet
Share
2.57K Views

Join the DZone community and get the full member experience.

Join For Free

The real name of the CSS variables is CSS Custom Properties is a draft standard (yes, when I wrote these lines, it is on Candidate Recommendation Snapshot), but it is widely supported by modern browsers.

CSS Variables

CSS variables allow us, like another kind of variable in another programming language, to store a value we can reuse across our document.

For example, if we define a CSS variable for the primary color doing the following: --primary-color: #f00;, then we can use it in any component like:

 
.my-component {
  color: var(--primary-color);
}


Usually, you “attach” your variable to :root, which means the variable will be available in all the document

 
:root {
  color: var(--primary-color);
}


In this example :root is the variable scope.

Using Together SCSS

If you want to assign values from SCSS variables to CSS variables, you can not do the “normal” notation:

 
// ❌ This doesn't work
$scss-var: #f00;
--my-var: $scss-var;


In the example, the value of --my-var is literally $scss-var, not the value of $scss-var, this behavior was done to provide maximum compatibility with the plain CSS.

To make it work, you need to use the Sass interpolation syntax: #{my scss script code}:

 
// ✅ This works
$scss-var: #f00;
--my-var: #{$scss-var};


Scope

The variables are only available in the element where it is defined and its children; that is the scope of the variable. Outside there, the variable doesn’t exist.

If you try to access to use a variable that is not in the scope, you will not get an error, but the property that is using the not existing variable will be ignored.

Hoisting

Like the JS variables, the CSS variables are moved to the top, so you can use them before defining them.

 
.my-element {
  color: var(--primary-color);
}
:root {
  --primary-color: #f00;
}


Override

As I mentioned before, the variables have a scope where the variable exists, but: what happens if a variable with the same name is defined in two scopes: It happens the same as in a JS variable; the near local scope overrides other values:

 
:root {
  --color: #0f0;
}
    
.my-element {
  --color: #0ff;
  color: var(--color);
}


This behavior is very convenient when we work with UI components with different styles depending on modifiers.

CSS Variables in UI components

Imagine we have a simple button component like that.

 
<button class="ui-button">
  Button content
</button>


 
.ui-button {
  background: #333;
  color: #fff;
  font-size: 12px;
  padding: 4px 10px;
}


This button has different variants by color (default, red and green) and size (default, small and big); using BEM, we can add a modifier class like .ui-button--green or .ui-button--big and use that to overwrite the styles, for example:

 
.ui-button {
  background: #333;
  color: #fff;
  font-size: 12px;
  padding: 4px 10px;
  
  &--green {
    background: #1F715F; 
  }

  &--big {
    font-size: 16px;
    padding: 6px 20px;
  }
}


This way works perfectly, but we need to know which properties to overwrite, and need to do it explicitly for each modifier, so it’s easy to forget something, or if we need to add a new property affected by the modifiers, add it in all of them

Suppose we rewrite the styles using CSS variables, parameterizing the component styles. In that case, we can override the CSS variable values for each modifier without changing the CSS styles itself for the modifiers, only changing the value of the variables:

 
.ui-button {
  --bg-color: #333;
  --text-color: #fff;
  --font-size: 12px;
  --padding: 4px 10px;
  
  background: var(--bg-color);
  color: var(--text-color);
  font-size: var(--font-size);
  padding: var(--padding);

  &--green {
    --bg-color: #1F715F;
  }

  &--red {
    --bg-color: #0ff;
  }

  &--big {
    --font-size: 16px;
    --padding: 6px 20px;
  }

  &--small {
    --font-size: 10px;
    --padding: 3px 5px;
  }
}


Variable Scope Priority

In CSS, the elements can use more than a class, so that means the element’s CSS variables have multiple scopes at the same level; for example, if we apply the green and red modifiers at the same time

 
<button class="ui-button ui-button--green ui-button--red">
  Green + red
</button>


Both ui-button--green and ui-button--red define the same --bg-color variable, What value will be applied to the element?

In cases like that, the class order is the priority, so the last class used overrides the value last, and its value is applied; in the example, the button will be red, but for <button class="ui-button ui-button--red ui-button--green"> the button will be green.

Summarizing

The use of CSS variables and scopes is a powerful tool when you are developing components in general. Still, if your components have modifiers, it requires extra work in the beginning to parameterize the component, but after that makes it simpler to create variants and modifiers.

CSS UI Language-oriented programming

Published at DZone with permission of Sergio Carracedo. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Detecting Network Anomalies Using Apache Spark
  • What Is JavaScript Slice? Practical Examples and Guide
  • 4 Best dApp Frameworks for First-Time Ethereum Developers
  • Reliability Is Slowing You Down

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: