Css Variables

From Logic Wiki
Revision as of 14:09, 5 September 2018 by AliIybar (Talk | contribs) (Created page with "Category:CSS To declare a variable, you first need to decide which scope the variable should live in. If you want it to be available globally, simply define it on the '''...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search


To declare a variable, you first need to decide which scope the variable should live in. If you want it to be available globally, simply define it on the :root pseudo class. It matches the root element in your document tree (usually the <html> tag).

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

The variable must start with two dashes.


To access a variable, you need to use the var() function, and pass in the name of the variable as the parameter.

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


Declaring a local variable

You can also create local variables, which are accessible only to the element it’s declared at and to its children. This makes sense to do if you know that a variable only will be used in a specific part (or parts) of your app.

For example, you might have an alert box which uses a special kind of color which aren’t being used other places in the app. In that case, it might make sense to avoid placing it in the global scope:

.alert {
  --alert-color: #ff6f69;
}

This variable can now be used by its children:

.alert p {
  color: var(--alert-color);
  border: 1px solid var(--alert-color);
}

Responsiveness

:root {
  --main-font-size: 16px;
}
media all and (max-width: 600px) {
  :root {
    --main-font-size: 12px;
  }
}

And with those simple four lines of code you have updated the main font size across your entire app when viewed on small screens

Accessing variables with JavaScript

var root = document.querySelector(':root');
var rootStyles = getComputedStyle(root);
var mainColor = rootStyles.getPropertyValue('--main-color');
console.log(mainColor); 
--> '#ffeead'

To update the CSS Variable simply call the setProperty method

root.style.setProperty('--main-color', '#88d8b0')

See Also https://scrimba.com/g/gcssvariables