This content originally appeared on DEV Community and was authored by Kiambuthi Kinuthia
to declare a variable prefix your variable name with two dashes then to use it, use the var()
function
/* -- declaring the variable. -- */
--variable_name: variable_value
/* -- accessing the variable. -- */
html {
font-family: var(--variable_name);
}
Variable Scope | Global or Local ?
Variables can be either scoped globally or locally. declaring your variables inside the :root
pseudo-class makes them available in the global scope and available for use throughout ythe stylesheet.
header {
--bg-color: red;
/* bg-color is only visisble to all children of the header element */
}
main {
background: var(--bg-color);
/* bg-color is undefined. */
}
/* to declare global variables place all variable inside the :root pseudo-class */
:root {
bg-color: red;
}
header {
background: var(--bg-color);
}
main {
background: var(--bg-color);
}
Common Use Cases
One way to use css variables is to save common colors or an entire color pallete which you can then use to style elements.
:root {
/* -- Use css variables to declare site colors -- */
--primary-color: black;
--secondary-color: gray;
--tetiary-color: white;
/* -- Color Palettes -- */
/* -- black color palette */
--black-clr-plt-1: rgb(0, 0, 0);
--black-clr-plt-2: rgb(30, 30, 30);
--black-clr-plt-3: rgb(60, 60, 60);
--black-clr-plt-4: rgb(90, 90, 90);
/* -- brown color palette -- */
--brown-clr-plt-1: rgb(60, 20, 20);
--brown-clr-plt-2: rgb(90, 30, 30);
--brown-clr-plt-3: rgb(120, 40, 40);
--brown-clr-plt-4: rgb(150, 50, 50);
}
/* -- styling -- */
body {
background: var(--brown-clr-plt-3);
color: var(--black-color-plt-1);
border: 1px solid var(--primary-color);
}
Providing Fallback Values
To provide a fallback value in case the variable is undefined, pass the fallback value as a second argument into the var()
function.
:root {
--site-font: 'Raleway';
}
html {
font-family: var('Raleway', monospace);
}
/* In this example if site-font is undefined, the monospace font is used. */
that's it, you're welcome to follow the journey onwards on my github
This content originally appeared on DEV Community and was authored by Kiambuthi Kinuthia
Kiambuthi Kinuthia | Sciencx (2021-09-24T16:17:28+00:00) CSS Variables | Learning CSS Best Practices – #01. Retrieved from https://www.scien.cx/2021/09/24/css-variables-learning-css-best-practices-01/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.