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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • CSS Hide and Seek: Choosing Between display: none and visibility: hidden
  • Subtitles: The Good, the Bad, and the Resource-Heavy
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!
  • Programmatic Brand Extraction: Pulling Logos, Colors, and Assets from Any URL

Trending

  • To Switch, or Not to Switch the AI Model
  • Part 1: Building Governed MCP Tool Services With Quarkus LangChain4j and Goose
  • Moving 900+ GB of Prometheus Without a Cutover Weekend
  • Kafka With Spring Boot: Introduction

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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.

By 
Sergio Carracedo
·
Mar. 09, 23 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
3.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

Related

  • CSS Hide and Seek: Choosing Between display: none and visibility: hidden
  • Subtitles: The Good, the Bad, and the Resource-Heavy
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!
  • Programmatic Brand Extraction: Pulling Logos, Colors, and Assets from Any URL

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook