CSS Variables
September 27, 2018
Definition
Create Variables
We can make custom properties with values that can be used in other declarations. These property names are prefixed with –, and used in the var( ) function.
- Define a root rule
- Put your variables inside of the root
(At the top of your CSS file)
:root {
--first-color: hsl(175, 49%, 42%);
}
Different Types of Variables
- A regular variable has two dashes
- --second-color: #ffff8c;
- A custom variable has @ sign
- @custom-media --min (width <= 600px);
Using Variables
// Using regular variables
#header {
background-color: var(--first-color);
color: var(--second-color);
}
// Using custom variables
@media (--min){
display: block;
}
Create and Use a Custom Selector
...
@custom-selector :--headings h1, h2, h3, h4, h5, h6;
}
:--headings {
margin: 0 0 1rem;
color: var(--first-color);
}
Create a more complicated variable
--my-button: {
display: inline-block;
padding: 6px;
background-color: var(--first-color);
...
}
.nav .my-button {
@apply --my-button;
@media (--min) {
display: block;
}
}
Note
This is one of the most useful features in CSS, but still new and experimental technology. Browser compatibility is pretty good, except for IE. You need the post
Reference
Do you know how to use CSS variables? [LINK]
Custom properties: CSS variables [LINK]