CSS Variable

From Logic Wiki
Jump to: navigation, search


The Old Way

#title{
 color: #ff6699;
}
.quote{
 color: #ff6699;
}

The New Way

Declaring a variable

:root {
   --red: #ff6699;
}

Referencing it

#title{
 color: var(--red);
}
.quote{
 color: var(--red);
}

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.

.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

In practice this means that you can, for example, change the variables based upon the width of the screen:

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

How to access 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 on the element in which the variables has been declared on and pass in the variable name as the first parameter and the new value as the second.

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


Functions

width: min(926px, 100% - 4rem)