Mastering CSS Variables and Unlocking Their Full Potential

CSS Variables, also known as Custom Properties, have revolutionized the way we manage styles and build maintainable, flexible stylesheets. They enable developers to store and reuse values throughout a stylesheet, making it easier to change themes, colors, fonts, and more with just a few updates. In this article, we’ll explore the best practices for using CSS variables, along with some helpful code examples.

Your Designer Toolbox Unlimited Downloads: 500,000+ Web Templates, Icon Sets, Themes & Design Assets

1. Defining and Using CSS Variables

To define a CSS variable, you must use the double hyphen (–) syntax. Typically, you’ll want to create your variables within the :root pseudo-class, which refers to the highest-level parent element in the DOM tree. This ensures that your variables are globally accessible.

:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --font-size: 16px;
}

body {
  font-size: var(--font-size);
}

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

button {
  background-color: var(--secondary-color);
}

In the example above, we’ve defined three CSS variables: –primary-color, –secondary-color, and –font-size. To use these variables, we use the var() function, which accepts the variable name as its argument.

2. Fallback Values

One of the great features of CSS variables is their ability to provide a fallback value. This is helpful when a variable may not be defined or supported by a particular browser. To provide a fallback value, include a second argument within the var() function.

body {
  font-size: var(--font-size, 16px);
}

In this example, if the –font-size variable isn’t defined, the browser will use the fallback value of 16px.

3. Leveraging Variables in Media Queries and Theming

CSS variables are incredibly useful when combined with media queries and theming. You can quickly and easily update your styles for different devices or themes by redefining the variable values.

:root {
  --font-size: 16px;
}

@media screen and (min-width: 768px) {
  :root {
    --font-size: 18px;
  }
}

body {
  font-size: var(--font-size);
}

In this example, we’ve updated the –font-size variable within a media query. When the screen width is at least 768px, the font size will automatically adjust to 18px.

4. Working with Calculated Values

CSS variables can be combined with the calc() function to create dynamic and flexible values.

:root {
  --base-padding: 10px;
}

.container {
  padding: calc(var(--base-padding) * 2);
}

In the example above, we’ve defined a base padding value and used it in combination with the calc() function to double the padding for the .container element.

5. Handling Colors with HSL and CSS Variables

When working with colors, using the HSL color format in combination with CSS variables makes it easier to create color schemes and adjust hues, saturation, and lightness.

:root {
  --primary-hue: 210;
  --primary-color: hsl(var(--primary-hue), 50%, 50%);
  --primary-color-light: hsl(var(--primary-hue), 50%, 75%);
  --primary-color-dark: hsl(var(--primary-hue), 50%, 25%);
}

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

a:hover {
  color: var(--primary-color-light);
}

a:active {
  color: var(--primary-color-dark);
}

In this example, we’ve used the HSL color format and CSS variables to create a primary color and its lighter and darker variations. By adjusting the –primary-hue value, you can change the color scheme throughout your stylesheet with ease.

6. JavaScript Interoperability

CSS variables can be accessed and manipulated using JavaScript, providing an additional layer of flexibility and dynamism. For instance, you can create user-customizable themes by modifying variables through JavaScript.

<button onclick="changeTheme()">Change Theme</button>

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%20%20function%20changeTheme()%20%7B%0A%20%20%20%20let%20root%20%3D%20document.documentElement%3B%0A%20%20%20%20let%20currentHue%20%3D%20parseInt(root.style.getPropertyValue('--primary-hue'))%3B%0A%20%20%20%20let%20newHue%20%3D%20(currentHue%20%2B%2030)%20%25%20360%3B%0A%20%20%20%20root.style.setProperty('--primary-hue'%2C%20newHue)%3B%0A%20%20%7D%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />

In the example above, clicking the “Change Theme” button will change the –primary-hue variable, effectively updating the primary color and its variations.

Wrapping Up

Variables have transformed the way we approach theming, responsiveness, and maintainability in our stylesheets. By following best practices such as global variable declaration, using fallback values, leveraging variables in media queries, working with calculated values, handling colors with HSL, and harnessing JavaScript interoperability, you’ll unlock their full potential.

With this newfound understanding, you can create more efficient, flexible, and dynamic stylesheets that adapt to different devices, user preferences, and themes with minimal effort.

How To Use a Python Variable in an External Javascript (Django)

One way to use a Python variable in an external Javascript is to declare the JS variable in the HTML template through the context object, then pass this variable to the external script code :

HTML
 
<script type="text/javascript"> 
  js_var_from_dj = "{{ django_var }}";
</script>
<script src="https://dzone.com{% static "js/js_file.js" %}" type="text/javascript"></script>

js_file.js :

Avoid Yoda Conditions in Perl You Should

I remember a brief time in the mid-2000s insisting on so-called “Yoda conditions” in my Perl. I would place constants to the left of equality comparisons. In case I accidentally typed a single = instead of ==, the compiler would catch it instead of blithely assigning a variable. For example:

Perl
 
if ( $foo == 42 ) { ... } # don’t do this
if ( 42 == $foo ) { ... } # do this
if ( $foo = 42  ) { ... } # to prevent this

And, because a foolish consistency is the hobgoblin of little minds, I would even extend this to string and relational comparisons.

Building Dark Mode

Like many companies, we have a Hack Week at Sentry. In 2017, we coded an app which blared entrance music for anyone who stepped foot in our office. In 2019, we encouraged folks to be nice on the Internet. Noble causes, sure, but for this year’s Hack Week I was determined to advance a cause near and dear to my cold British heart: dark mode.

Little did I know that what started as a minor hack week project would become a major lift that included pantone colors, hex codes, and all sorts of variables.

let vs. const

There are multiple ways to declare variables in JavaScript. We had var, and while that still works like it always has, it is generally said that let and const are replacements to the point we rarely (if ever) need var anymore. This doodle explanation does a pretty good job, if you need a refresher.

What is up for debate is the general coding style of when you should pick one or the other. There are situations where you have to use let, like when you need to redeclare the variable since const doesn't let you do that. But does that mean you should use const in every single situation where you don't?

Dan Abramov covers the "controversy". It's a very well articulated point and counterpoint of both sides with literal lists that compare the two.

My favorite is the first point on both.

The argument that prefers const when possible:

One Way to Do It: It is mental overhead to have to choose between let and const every time. A rule like “always use const where it works” lets you stop thinking about it and can be enforced by a linter.

The argument that prefers let when possible:

Loss of Intent: If we force const everywhere it can work, we lose the ability to communicate whether it was important for something to not be reassigned.

All five points on both sides are worth a read.

I love Dan's conclusion: "I don’t care." This is something that can be linted and auto-fixed. You can have an opinion if you want, just like tabs vs. spaces, but it's something that automation handles in the day-to-day.

Direct Link to ArticlePermalink

The post let vs. const appeared first on CSS-Tricks.