Today I Learned

hashrocket A Hashrocket project

Native CSS Variables

CSS variables are normally associated with the pre-processor languages like SASS. But css has its own native variables as well. Declare them like so:

element { 
  --black-grey: #111111;
}

And then use them with the var function like this:

element { 
  background-color: var(--black-grey);
}

In the above example if --black-grey is not set then the background-color will fallback to the inherited value. You can provide a default value for the variable if you anticipate it may not be set:

element {
  background-color: var(--black-grey, black);
}

Variables behave just like any other inherited or cascading properties and if you'd like them available for entire stylesheets then you would need to declare them in :root.

:root {
  --one-fathom: 16rem;
}

This css feature is safe to use everywhere but IE, but it is only recently safe. Firefox enabled this feature by default in version 56 released in Sept 2017.

You can read about them in the Mozilla Docs or the original W3C editor's draft.

See More #html-css TILs