CSS Variables
Overview
CSS variables are a powerful tool for managing a website's design. They allow for the creation of reusable values that can be used throughout a stylesheet, helping to maintain design congruency. This activity will introduce you to CSS variables and how to use them in your projects.
"Complex websites have very large amounts of CSS, and this often results in a lot of repeated CSS values. For example, it's common to see the same color used in hundreds of different places in stylesheets. Changing a color that's been duplicated in many places requires a search and replace across all rules and CSS files. Custom properties allow a value to be defined in one place, then referenced in multiple other places so that it's easier to work with." - MDN
Prepare
How are CSS variables used in website projects?
The :root Pseudo-Class
- The
:root
pseudo-class is used to select the root element (html
) of the document. - It is common to see the
:root
rule at the top of the CSS document, especially since global CSS variables will be declared within that rule.
Writing Global CSS Variables
- Global CSS variables are declared within the
:root
selector. - Global CSS variables are declared using the
--
prefix followed by the variable name, of your choice but follow naming conventions.Using Kebab notation with hyphens (-) is OK when naming CSS variables, e.g., primary-color
- Global CSS variables are used by calling the variable name with the
var()
function.
:root {
--heading-background-color: #f06;
--heading-text-color: #333;
--heading-font: 'Montserrat', Helvetica, sans-serif;
--padding: 1rem;
--border: 1px solid rgb(0 0 0 / 0.1);
}
/* Some example variable use in declarations. */
h1 {
background-color: var(--heading-background-color);
color: var(--heading-text-color);
font-family: var(--heading-font);
padding: var(--padding);
}
aside {
margin: 10px auto;
padding: var(--padding);
box-shadow: 0 0 10px rgb(0 0 0 / 0.1);
}
Activity Instructions
- In your wdd130 root site, open up your existing styles.css file.
- Create a
:root {}
rule at the top of the file. - Review your course home page CSS a look for colors, fonts, sizes, and other values that are repeated.
- Replace those repeated CSS property values with CSS variables.
- Test your page in your local browser using Live Server.
- Commit and sync/push your work to your wdd130 GitHub Pages enabled repository.
- Share your work with others on Microsoft Teams.
Optional Resources
- :root - MDN
- var() - MDN
- CSS Variables - MDN
- Using CSS custom properties (variables) - MDN