DEV Community

Cover image for CSS Variables

CSS Variables

Samantha Ming on February 13, 2020

Move over Sass, we have #CSS variables! I still love Sass of course. But it’s great native CSS supports this. No need for a preprocessor & no...
Collapse
 
adam_cyclones profile image
Adam Crockett 🌀 • Edited

Can I just add that if you use calc (or nested calc) and JavaScript update vars and CSS vars you can have it so one js update of a variable changes a lot of logic which can all be handled in the CSS. It's a very powerful workflow. In fact so much so I am writing a language like tailwind just for this workflow.

Collapse
 
samanthaming profile image
Samantha Ming

that's super cool! ...btw, do you mind explaining nested calc? 🙂

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Sure, it's not widely known or atleast it wasn't usefull to nest calc function given that before variables, values where essentially hard coded.

:root {
   --grid-colomns: 12;
}

.thing {
    width: calc(100vw / var(--grid-columns) * calc(var(--grid-columns) * 2)
}

Okay this is a terrible example but it does illustrate how CSS can become config based and calc can do most of the work.

Thread Thread
 
samanthaming profile image
Samantha Ming

Oh cool!!! That’s super neat...I got to read this a few more time to understand it 😅...thanks so much for explaining it! Love learning new things ⭐️⭐️⭐️

Thread Thread
 
adam_cyclones profile image
Adam Crockett 🌀

Your not the only one, I found this out recently, didn't know calc was nestable, your most welcome.

Thread Thread
 
frontendprof profile image
AbdulMalik

Can you explain what the code snippet does, please. Or can you direct me to some articles in which it is elaborated your topic please.

Thread Thread
 
adam_cyclones profile image
Adam Crockett 🌀 • Edited

I wasn't sure what specifically you wanted to know but, AFAIK, there are no specific posts on the topic, I may have one (I have hundreds of posts so it might take some time to find).

What does it do? its a simple implementation of a 12 column grid layout normally calculated via a pre-processor, what it does is not so important, how it does it is whats interesting here.

The short story is:

CSS is calculated by the browser, you might consider this "run-time" for css, at this point a few things are possible, bellow is a broken down list of the things I have use and what they do:

vw units: 100 vw is the full viewport width as computed pixels, it is not 100% of the parent container.
css variables: --some-variable: red; stores a value, var(--some-variable) computes the value
calc(): runtime maths such as calc(100% + 20px) which is cool, but you can also just add or subtract numbers and make calculations normally computed in css pre-processors

Oh yes and lastly, I nested a calc() inside another calc to achieve complex maths

Thread Thread
 
frontendprof profile image
AbdulMalik

Thank you for the reply.
But I was implying explanation of your nested calc function. It would be great if you could elaborate on that one as well please, if you don't mind of course.

Thread Thread
 
adam_cyclones profile image
Adam Crockett 🌀 • Edited

developer.mozilla.org/en-US/docs/W...

CSS calc 'calculate' is built into CSS and can be nested, the full documention can be found above.

However nesting refers to the fact that calc exaluates to a unit so then calc(calc(2px + 4px) + 4px)

10 pixels

But this is particularly useful for complex math with variables because variables can change in media query and stateful circumstances (:hover, :focus etc)

Thread Thread
 
frontendprof profile image
AbdulMalik

thanx

Collapse
 
nanouchkaya profile image
Claudine • Edited

Thank you so much! I've always been a CSS advocate but since I discovered Sass and its variables and functions, I tend to neglect CSS... So, I'm excited to get back in tiny projects without preprocessor and, as you said, with JS in the party, it's going to get crazy 💯

Collapse
 
samanthaming profile image
Samantha Ming

I was that way for a long time, Sass become a must have for all my projects and I just bared with the burden of installing it even on the small apps 😓. No more! Now i can go native all the way. Very nice for sure! thumbs up to the CSS folks 👍

Collapse
 
rodiongork profile image
Rodion Gorkovenko

That feeling when you are developer for many years, though mostly not front-end, but doing UI chores for work or in own side-projects... And then suddenly learns such great news by lazily reading topics on DEV.

Thank you, Samantha! God bless your efforts on sharing such things to us, lazy people! :)

Collapse
 
samanthaming profile image
Samantha Ming

lol, awesome! so glad you found it helpful! 😆

for an even lazier experience, feel free to check out my twitter account. and you can skip reading the code notes completely 😆

I'll even include the link to make things easier 😂 twitter.com/samantha_ming

Collapse
 
konrud profile image
Konstantin Rouda

As far as I remember syntax in the following example is invalid:

:root {
  --value: 5;
}

div {
  padding: var(--value) px; /* 5px */
}

We can not build up values in CSS the way it depicted in the example above,
we should always combine it with the calc(), like this:

:root { --value: 5; } 
div { 
 padding: calc(var(--value) * 1px); /* 5px */ 
}  
Collapse
 
samanthaming profile image
Samantha Ming

Great catch!!!! Let me fix that, thank you!!!! 💪

Collapse
 
azzcatdesign profile image
Catherine Azzarello

Thanks, Samantha!

I'm totally on board with CSS variables! I've got CodePens where I worked out responsive typography, spacers, and containers using global and scoped variables plu with calc(). Even took it further with HSL colors and abstracting the separate values to local variables for button colors. You can't do the same kind of color edits in CSS with variables as you can with SCSS ie: darken($color, 10%) but I've found I'm not missing SCSS variables for color, just organizing differently.

Collapse
 
samanthaming profile image
Samantha Ming

OH that's super cool! If you don't mind, can you send me the link to it? Would love to see how you organize your code with css variables 😄

Collapse
 
azzcatdesign profile image
Catherine Azzarello

Sure! Layout Overlay with Container & Grid Modifiers codepen.io/azzcatdesign/pen/PoovWmp; Type Variables: Responsive Scale Ratios codepen.io/azzcatdesign/pen/yLLWgbq; Spacing Variables (Fibonacci) codepen.io/azzcatdesign/pen/YzzbNQ...; and HSL Custom Properties for States codepen.io/azzcatdesign/pen/WNNBRj...

Thread Thread
 
samanthaming profile image
Samantha Ming

This is fantastic! Thanks for sharing! Let me add this to my code notes 👏

Collapse
 
cristijora profile image
Cristi Jora

Yess CSS variables ftw. It's time to slowly get rid of scss. Other then nesting and some mixins it doesn't add a bunch of value now since css gets more of these features out of the box.

Some neat things you can do with css variables is easily control font sizes, spacings, colors on different viewports/pages. You could even do dark mode really easily by changing some css variables.

Collapse
 
samanthaming profile image
Samantha Ming

Dark mode is a huge beneficiary of CSS variable! let me add your input to my code notes! thanks for sharing 👏

Collapse
 
dillonheadley profile image
Dillon Headley • Edited

css vars are awesome. Here's some cool things i've been using them for.

Flexible container widths without having to overwrite the rule:

:root {
  --container-sm: 60rem;
  --container-md: 110rem;
  --container-lg: 126rem;
}


.g-container {
  max-width: var(--container-width, var(--container-md));
  width: calc(100% - var(--container-gap, 2rem));
  margin-left: auto;
  margin-right: auto;
}

...

<article class="c-supportPlans g-container">
...

.c-supportPlans {
  --container-width: var(--container-xl);
  ...
}

Font styles management:

  --muli-1: 800 1.6rem/1.25 'Muli', sans-serif;
  --muli-2: 700 1.4rem/1.25 'Muli', sans-serif;
  --muli-3: 400 1.2rem/2 'Muli', sans-serif;

  --open-sans-1: 800 3.2rem/1.375 'Open Sans', sans-serif;
  --open-sans-2: 400 2.4rem/1.167 'Open Sans', sans-serif;
  --open-sans-3: 800 2rem/1.4 'Open Sans', sans-serif;

...
.c-supportPlans-plan h2 {
  font: var(--open-sans-3);
}

and declarative simple animations:

@keyframes fromTo {
  from {
    transform: var(--from);
  }
  to {
    transform: var(--to);
  }
}

.c-industriesBanner-list {
  --from: translateX(0);
  --to: translateX(calc(-100% + -3rem));
  animation: linear 20s fromTo infinite;
  display: grid;
  grid-gap: 3rem;
  gap: 3rem;
  grid-auto-flow: column;
  grid-auto-columns: 15rem;
}

codepen.io/dillonbheadley/pen/oNXNyPa

fun stuff!

Collapse
 
samanthaming profile image
Samantha Ming

Thanks for sharing this @dillonheadley . Awesome work! It's always so helpful to see how people implement the tech in their own project. Let me link this in the code notes 👏

Collapse
 
dillonheadley profile image
Dillon Headley

For sure! 👍🏼 Love your posts btw!

Collapse
 
dillonheadley profile image
Dillon Headley

Here's one more to manage buttons with vars: codepen.io/dillonbheadley/pen/PoqWqxq

Collapse
 
islam profile image
Islam Sayed

Your way of explaining things are funny and awesome.

Collapse
 
samanthaming profile image
Samantha Ming

Hahaha thanks! Finally someone actually said it’s funny! I failed as a stand up comic, so I’m practicing my routine in programming articles lol 😂

Collapse
 
waylonwalker profile image
Waylon Walker

Such an amazing well written article @Samantha Ming! I 💕 your images and use of emoji is 👌.

Sadly I am in a company with crazy high IE usage. I get reports on occasion that things are broken.... Looks fine to me. $H!1! I forgot to double check IE, then am amazed at what seemingly simple things IE is missing.

Collapse
 
samanthaming profile image
Samantha Ming

Thank you for the kind words, glad you it helpful 😊

IE support 😖
@jhildenbiddle shared a polyfill he wrote that might help > dev.to/jhildenbiddle/comment/lmi3

Collapse
 
waylonwalker profile image
Waylon Walker

Super thanks for the polyfill!! I will consider that. I had no idea such a core css feature could be polyfilled.

For now I have mostly settled on using styled components

Collapse
 
jhildenbiddle profile image
John Hildenbiddle

Those looking for IE/legacy support for CSS custom properties (i.e. "CSS variables") can check out css-vars-ponyfill. Forgive the self promotion (I am the author), but I thought it would be helpful for those still burdened--as I was not too long ago--with IE/legacy support.

Collapse
 
samanthaming profile image
Samantha Ming

This is great John! Also thank you for being so transparent. I'll add it to my code notes in the community section 😊

Collapse
 
clozach profile image
Chris Lozac'h

Great article, Samantha! The only question I had at the end was how to do the CSS ↔️ JS round trip for a global variable, as opposed to (as I understand it) your final example, which shows how to do it for a variable in local scope?

Collapse
 
samanthaming profile image
Samantha Ming • Edited

Great question @clozach ! You will have to go with the getComputedStyle route, but instead of passing the element, you just pass in document.documentElement. So something like this:

:root {
  --color: red;
}
getComputedStyle(document.documentElement).getPropertyValue('--color');

(Let me update my official notes too 👏)

Collapse
 
daveblythe profile image
Dave Blythe (he/him)

Great content, Samantha!

I had just recently started using CSS variables in some of my own projects. Like many other things that we learn (and re-learn) constantly... it was one of those I'll learn just enough to accomplish my immediate task... and not any more.

Reading your post, I now realize/understand things like the ability to override/scope the globals based on a particular context (my #1 takeaway), as well as becoming aware that there's a lot more value than I had begun to use.

As someone else mentioned... the delivery/humor makes it a fun read, too!

Collapse
 
samanthaming profile image
Samantha Ming

Yay, thanks for the positive reinforcement! Making it fun to read is my ultimate goal! I remeber really struggling reading tech docs, so now I can write my own blog posts, I want to make sure it’s at least fun to read and make the programming journey a bit easier for others 😊

Collapse
 
samanthaming profile image
Samantha Ming

I definitely has used CSS variable on the global level more. But again, I've mainly used it on smaller apps. But I'm sure if my app was bigger, that finer control with local variable might be handy. To complete my toolbox knowledge, I think it's good to know so I can use it when I cross that path 😊

The interesting thing about IE users is that it's a company restriction. Definitely not necessarily lower means or developing countries, some of them are in the financial sector, doing very well. But for some reason, they're stuck using IE. (I'm pretty sure those employees wish their employers would stop using IE 😅). Hopefully, one day we can convince all these companies to stop using IE (cause when the buck stops, the support will stop as well) I think that will be a very happy day 😂

Collapse
 
mzaini30 profile image
Zen

Wow. It's new knowledge for me

Collapse
 
samanthaming profile image
Samantha Ming

Yay, glad to share something new with you 👏👏

Collapse
 
mzaini30 profile image
Zen

Yap. I was bookmark this post. I will use it in my next projects

Collapse
 
samanthaming profile image
Samantha Ming

Welcome back to web dev! You might also find my other tidbits helpful, it might help with your catch up 😊

samanthaming.com/tidbits/

Collapse
 
samanthaming profile image
Samantha Ming

The repair shop is my best friend 😂

Supporting multiple browsers is okay, but IE is always ruining my day 🤦‍♀️

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

CSS variables are great! I have yet to make anything complex enough to need them, but I'll use them when I do!

Collapse
 
samanthaming profile image
Samantha Ming

The great thing is you don't need it for anything complicated. I've been using it for my smaller apps too. Very handy to keep my code clean 😄

I used it for my "not fancy app challenge" > github.com/samanthaming/not-fancy-...

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

True😌 Without repeated CSS though, I have yet to hit the biggest use case for them. What little CSS I need doesn’t even benefit from reduction via variable definitions, as nothing is reused.

Collapse
 
basarozcan profile image
Başar Özcan

Perfect tutorial for CSS variables, thank you. Finally we can use variables in small projectd w/o SASS :)

Collapse
 
dmahely profile image
Doaa Mahely

Awesome article!

Collapse
 
samanthaming profile image
Samantha Ming

Thanks for reading!! 👏👏

Collapse
 
brovic profile image
Victor Ordu

So is this CSS 4 or what? Thanks for a very enlightening post.

Collapse
 
samanthaming profile image
Samantha Ming

I think they move away from that type of versioning > rachelandrew.co.uk/archives/2016/0...

Here's the official draft here 🙂 > drafts.csswg.org/css-variables/#de...

Collapse
 
samanthaming profile image
Samantha Ming

No worries Harlin!l 🙂 Web dev moves so quickly, it’s hard to keep up. That’s why I created the tidbits - a hopefully easy to read for folks to stay in the loop. I’ll keep sharing more as I find them 👏

Collapse
 
max_tulian profile image
Max (he/his)

Wow, I didn’t know about css variables:) Thanks for share, I do love sass but with this improvement pure css is more interesting

Collapse
 
samanthaming profile image
Samantha Ming

Totally! CSS is moving in the right direction! Sass is still great, but now i just mainly use it for bigger apps to justify the installation 😆 Otherwise vanilly css all the way 💪

Collapse
 
iamsbharti profile image
Iamsbharti

This is so lovely 🤗🤗

Collapse
 
samanthaming profile image
Samantha Ming

CSS variables are indeed super lovely! ⭐️

Collapse
 
maualkla profile image
Mauricio Alcala

Super! Thanks for the clear explanation Samantha.

Collapse
 
samanthaming profile image
Samantha Ming

Thanks for reading! Glad it makes sense 😄👏