DEV Community

Kiambuthi Kinuthia
Kiambuthi Kinuthia

Posted on

CSS Variables | Learning CSS Best Practices - #01

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
}

Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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. */
Enter fullscreen mode Exit fullscreen mode

that's it, you're welcome to follow the journey onwards on my github

Top comments (0)