Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

HTML CSS - CSS Variables

Using CSS variables for reusable values

CSS variables, also known as custom properties, allow you to store values that can be reused throughout your CSS. This makes it easier to manage and update styles consistently across a website. This tutorial covers how to use CSS variables for reusable values.

Key Points:

  • CSS variables store reusable values that can be applied to multiple properties.
  • Variables are defined using the --variable-name syntax and accessed using the var(--variable-name) function.
  • CSS variables can be defined globally in the :root selector or locally within a specific selector.

Defining CSS Variables

CSS variables are defined using the --variable-name syntax. Here is an example:


:root {
    --main-bg-color: lightblue;
    --main-text-color: #333;
    --main-padding: 10px;
}
            

Using CSS Variables

CSS variables are accessed using the var(--variable-name) function. Here is an example:


.variable-example {
    background-color: var(--main-bg-color);
    color: var(--main-text-color);
    padding: var(--main-padding);
}
            
This is an example using CSS variables.

Global and Local Variables

CSS variables can be defined globally in the :root selector, making them available throughout the entire document. They can also be defined locally within a specific selector. Here is an example:


:root {
    --global-color: lightblue;
}

.container {
    --local-padding: 20px;
}

.global-example {
    background-color: var(--global-color);
}

.local-example {
    padding: var(--local-padding);
}
            
This is an example using a global CSS variable.
This is an example using a local CSS variable.

Fallback Values

You can provide fallback values for CSS variables in case the variable is not defined. This is done by adding a second argument to the var() function. Here is an example:


.example {
    color: var(--undefined-variable, red);
}
            
This example uses a fallback value.

CSS Variables in Media Queries

CSS variables can be used within media queries to adjust styles based on different conditions. Here is an example:


:root {
    --main-bg-color: lightblue;
}

@media (max-width: 600px) {
    :root {
        --main-bg-color: lightcoral;
    }
}

.variable-example {
    background-color: var(--main-bg-color);
}
            
Resize the window to see the background color change.

Summary

In this tutorial, you learned about using CSS variables for reusable values. CSS variables allow you to store values that can be reused throughout your CSS, making it easier to manage and update styles consistently. You explored defining and using CSS variables, global and local variables, fallback values, and using CSS variables in media queries. Understanding and using CSS variables is essential for creating maintainable and scalable web designs.