WDD 130: Web Fundamentals

CSS Variables

Why: Overview

CSS Variables are a powerful tool for managing the design of a website. They allow for the creation of reusable values that can be used throughout a stylesheet thus maintaining the 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?

Where: The :root Pseudo-Class

How: Writing Global CSS Variables

:root {
  --heading-background-color: #f06;
  --heading-text-color: #333;
  --heading-font: 'Montserrat', Helvetica, sans-serif;
  --padding: 1rem;
  --border: 1px solid rgba(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 rgba(0,0,0,0.1);
}

Activity Instructions

  1. In your wdd130 root site, open up your existing styles.css file.
  2. Create a :root {} rule at the top of the file.
  3. Review your course home page CSS a look for colors, fonts, sizes, and other values that are repeated.
  4. Replace those repeated CSS property values with CSS variables.
  5. Test your page in your local browser using Live Server.
  6. Commit and sync/push your work to your wdd130 GitHub Pages enabled repository.
  7. Share your work with others on MS Teams.

Optional Resources