Courses Learn Blog Contact
Get Started →
Lesson 16

CSS Variables and Debugging With DevTools

Learn to use CSS custom properties variables with DevTools debugging to simplify styling and diagnose layout issues efficiently.

Frontend Development Month 1: HTML, CSS & Tailwind 13 min read Free

Webbo3 Frontend Development · Month 1 · Lesson 16

CSS Variables and Debugging With DevTools

Learn to use CSS custom properties variables with DevTools debugging to simplify styling and diagnose layout issues efficiently.

CSS Variables and Debugging With DevTools — lesson cover

When you're building a website, you often find yourself using the same colours, fonts, and spacing in many different places. If you want to change one of these values, you have to search through your entire stylesheet to find every instance of it and update it manually. This can be time-consuming and error-prone, especially if you have a large and complex stylesheet. You might end up missing some instances of the value, or accidentally changing the wrong thing, which can lead to inconsistencies in your design. By the end of this lesson, you will be able to organise your stylesheet in a way that makes it easy to make changes like this. You will learn how to use CSS variables to define a value in one place, and then use it throughout your stylesheet. This means that if you want to change the value, you only have to edit it in one place, and the change will be applied everywhere. This will save you time and reduce the risk of errors. You will also learn how to use the browser's DevTools to diagnose problems with your layout, instead of just guessing at what might be wrong. You will learn how to use DevTools to inspect the elements on your webpage, and see exactly what styles are being applied to them. You will also learn how to use the DevTools to experiment with different styles and see the results in real-time, without having to edit your stylesheet. This will give you a much better understanding of how your stylesheet is working, and make it easier to track down and fix problems. By the end of this lesson, you will have the skills you need to take control of your stylesheet and make changes with confidence.

What you need before starting

Everything from the previous lesson, and the project folder you have been building in. Work along in your own editor as you read — this lesson is written to be typed, not skimmed.

CSS Variables and Custom Properties

Declaring Custom Properties

CSS variables, also known as custom properties, allow you to store and reuse values in your CSS code. To declare a custom property, you use the -- prefix followed by a name, and then assign it a value. A common practice is to declare custom properties on the :root pseudo-class, which represents the root element of the document, usually the html element.

This allows you to access these properties from any part of your CSS code. For example:

CSSExample and result
:root {
  --primary-color: #3498db;
  --secondary-color: #f1c40f;
  --font-size: 16px;
}
Result

In this example, we declare three custom properties: --primary-color, --secondary-color, and --font-size.

Using Custom Properties with var()

To use a custom property in your CSS code, you use the var() function, passing the name of the property as an argument. For example:

JavaScriptExample — try it in your editor
body {
  background-color: var(--primary-color);
  font-size: var(--font-size);
}

This sets the background color of the body to the value of --primary-color and the font size to the value of --font-size.

A common mistake beginners make is forgetting to use the var() function when using custom properties. Without var(), the browser will treat the custom property as a regular property and try to apply its value directly, which will result in an error. To spot this mistake, look for custom properties used without var() and add it to fix the issue.

Building a Design Token Set

Colour, Spacing, and Type

A design token set is a collection of reusable values that define the visual design of your application. Using custom properties, you can build a design token set for colour, spacing, and type.

For example:

JavaScriptExample — try it in your editor
:root {
  --primary-color: #3498db;
  --secondary-color: #f1c40f;
  --background-color: #f9f9f9;
  --font-size: 16px;
  --line-height: 1.5;
  --margin: 16px;
  --padding: 16px;
}

body {
  background-color: var(--background-color);
  font-size: var(--font-size);
  line-height: var(--line-height);
  margin: var(--margin);
  padding: var(--padding);
}

header {
  background-color: var(--primary-color);
  color: #fff;
}

In this example, we define a design token set with custom properties for colour, spacing, and type, and use them to style the body and header elements.

Editing Live to Test a Fix

Using DevTools to Test Changes

When debugging your CSS code, you can use the browser's DevTools to edit your code live and test changes before committing them. To do this, open DevTools by pressing F12 or right-clicking on an element and selecting "Inspect". Then, find the element you want to edit and click on it to select it.

In the Styles tab, you can edit the CSS rules applied to the selected element. You can add, remove, or modify rules to test different changes. For example, you can change the value of a custom property to see how it affects the design.

Beginners often make the mistake of editing the code in DevTools and forgetting to update the actual code. To avoid this, make sure to update your code files with the changes you make in DevTools.

Using the Computed Tab

The Computed tab in DevTools shows the final computed values of an element's styles, taking into account all the CSS rules applied to it. This can be helpful when debugging issues with custom properties, as it shows the actual values used by the browser.

For example, if you have a custom property --primary-color with a value of #3498db, the Computed tab will show the computed value of the background-color property as rgb(52, 152, 219), which is the RGB equivalent of #3498db.

By using the Computed tab, you can see how custom properties are being used and debug issues with your design token set.

CSS Variables and Debugging With DevTools — illustration

CSS Variables and Fallback Values

Understanding Fallback Values

CSS variables, also known as custom properties, allow you to store and reuse values in your stylesheet. One important aspect of CSS variables is fallback values. A fallback value is a default value that is used when the CSS variable is not defined. This ensures that your stylesheet does not break if a variable is not defined.

A common mistake beginners make is not providing fallback values for their CSS variables. This can lead to unexpected behavior or errors in their stylesheet.

Using Fallback Values

To use a fallback value, you can use the var() function in CSS, which takes two arguments: the name of the CSS variable and the fallback value. For example:

JavaScriptExample — try it in your editor
:root {
  --primary-color: #333;
}

.button {
  background-color: var(--primary-color, #666); /* #666 is the fallback value */
}

In this example, the background color of the button will be #333 if the --primary-color variable is defined, and #666 if it is not.

Organising a Stylesheet in a Predictable Order

Importance of Order

When writing a stylesheet, it's essential to organize your code in a predictable order. This makes it easier to maintain and debug your code. A common mistake beginners make is not following a consistent order in their stylesheet, leading to confusing and hard-to-debug code.

Recommended Order

A recommended order for a stylesheet is:

  • Variables and constants (e.g., CSS variables, font sizes)
  • Reset or normalize styles (e.g., box sizing, margin, padding)
  • Layout styles (e.g., display, flexbox, grid)
  • Component styles (e.g., buttons, forms, navigation)
  • Utility styles (e.g., text alignment, color)

Following this order helps to ensure that your stylesheet is easy to read and maintain.

JavaScriptExample — try it in your editor
/* variables and constants */
:root {
  --primary-color: #333;
}

/* reset or normalize styles */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* layout styles */
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* component styles */
.button {
  background-color: var(--primary-color);
  color: #fff;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

/* utility styles */
.text-center {
  text-align: center;
}

This example demonstrates a stylesheet organized in a predictable order, making it easier to maintain and debug.

Debugging with DevTools: The Box Model Panel

Understanding the Box Model

The box model is a fundamental concept in CSS, representing the structure of an HTML element as a rectangular box. The box model consists of four parts: content, padding, border, and margin. Understanding the box model is crucial for debugging layout issues.

Using the Box Model Panel in DevTools

The box model panel in DevTools provides a visual representation of the box model for a selected element. To access the box model panel, open DevTools, select the Elements tab, and click on an element in the HTML tree. The box model panel will be displayed in the Styles tab.

A common mistake beginners make is not using the box model panel to debug layout issues. The box model panel helps you identify and fix issues related to padding, margin, border, and content size.

For example, if you have an element with a width of 100px, but it's taking up more space than expected, you can use the box model panel to see if there's any padding or margin applied that's causing the issue.

CSS Variables

Why Variables Beat Find-and-Replace

Imagine you are building a website and you want to use the same color for the background, buttons, and headings. Without variables, you would have to repeat the color code everywhere you want to use it. If you then decide to change the color, you would have to find and replace the color code in every place you used it. This can be time-consuming and prone to errors.

CSS variables, also known as custom properties, allow you to define a variable and reuse it throughout your CSS code. This makes it easier to maintain and update your styles.

JavaScriptExample — try it in your editor
/* defines a variable named --main-color */
:root {
  --main-color: #3498db;
}

/* uses the variable for the background color */
body {
  background-color: var(--main-color);
}

/* uses the variable for the button background color */
button {
  background-color: var(--main-color);
}

In this example, the variable --main-color is defined in the :root block and then used in the body and button blocks. If you want to change the color, you only need to update the variable definition in one place.

Common Mistake

A common mistake beginners make is forgetting to use the var() function when using a CSS variable. For example, writing background-color: --main-color; instead of background-color: var(--main-color);. This will not work as expected, because --main-color is just a string without the var() function.

CSS Variables and Debugging With DevTools — illustration

DevTools

Inspecting an Element

To inspect an element, right-click on it in the browser and select "Inspect" or "Inspect element". This will open the DevTools panel. In the Elements tab, you can see the HTML structure of the page and the styles applied to each element.

Reading the Styles Panel

In the Styles panel, you can see all the CSS rules that apply to the selected element. The rules are listed in order of precedence, with the most specific rules at the top. You can also see which rules are overridden by other rules, indicated by a strikethrough.

For example, if you have two rules that set the background color, the second rule will override the first one. The first rule will be crossed out in the Styles panel, indicating that it is not being applied.

CSSExample and result
/* rule 1 */
body {
  background-color: #f2f2f2;
}

/* rule 2 */
body {
  background-color: #ffffff;
}
Result

In this example, the second rule will override the first one, and the background color will be #ffffff. The first rule will be crossed out in the Styles panel.

Why Rules Are Crossed Out

Rules can be crossed out for several reasons, including:

  • The rule is overridden by a more specific rule.
  • The rule is applied to an element that does not match the selector.
  • The rule is invalid or contains a syntax error.

By checking the Styles panel, you can see why a rule is not being applied and make the necessary changes to fix the issue.

Debugging Layout Issues

Finding the Element Causing Horizontal Overflow

Horizontal overflow occurs when an element is wider than its parent element, causing a scrollbar to appear. To find the element causing the horizontal overflow, you can use the DevTools Elements tab.

First, select the element that you think is causing the overflow. Then, in the Styles panel, check the box next to "overflow" to see if it is set to "visible". If it is, try setting it to "hidden" or "auto" to see if that fixes the issue.

Next, check the element's width and margin properties. If the width is set to a fixed value, try changing it to a relative value, such as a percentage. If the margin is set to a large value, try reducing it or setting it to "auto".

CSSExample and result
/* example of an element causing horizontal overflow */
div {
  width: 1200px; /* fixed width */
  margin: 20px; /* large margin */
}
Result

In this example, the div element has a fixed width of 1200px and a large margin of 20px. This can cause horizontal overflow if the parent element is not wide enough. By changing the width to a relative value or reducing the margin, you can fix the issue.

Do this now

Set aside about 30-45 minutes to complete this exercise, depending on how complex your project is. This task involves going through your CSS files and replacing all the hard-coded colour and spacing values with variables, then using DevTools to test and adjust your new variables.

Here's a step-by-step guide to help you through the process:

  1. Open your project in a code editor and locate all the CSS files.
  2. Identify all the hard-coded colour values (like #FFFFFF or rgb(255, 0, 0)) and spacing values (like 10px or 2em) in your CSS files.
  3. Replace each hard-coded value with a variable. For example, you can define a variable --primary-color: #3498db; and then use var(--primary-color) wherever you need that colour.
  4. Make sure to define all your variables in a :root block at the top of your main CSS file, so they are accessible throughout your project.
  5. Save your changes and open your project in a web browser.
  6. Open DevTools by pressing F12 or right-clicking on the page and selecting "Inspect" (the exact method may vary depending on your browser).
  7. In DevTools, switch to the "Elements" tab and select an element that uses one of your new variables.
  8. In the "Styles" panel, find the variable you want to change and click on it to edit its value. You can change the colour or spacing live and see the results immediately.

How to know you got it right

Here's a checklist to verify that you've completed the exercise correctly:

  • All hard-coded colour and spacing values have been replaced with variables.
  • Variables are defined in a :root block and are accessible throughout the project.
  • Changes made to variables in DevTools are reflected live in the browser.

Common mistakes

  • Forgetting the double dash prefix:
    JavaScriptExample — try it in your editor
    :root { var: color; }
    happens because beginners miss the rule, fix by using
    JavaScriptExample — try it in your editor
    :root { --var: color; }
  • Using variables before declaration:
    JavaScriptExample — try it in your editor
    background-color: var(--color); :root { --color: blue; }
    occurs because order matters, fix by declaring variables first:
    JavaScriptExample — try it in your editor
    :root { --color: blue; } background-color: var(--color);
  • Misspelling variable names:
    JavaScriptExample — try it in your editor
    :root { --colour: blue; } background-color: var(--color);
    happens due to typos, fix by ensuring correct spelling:
    JavaScriptExample — try it in your editor
    :root { --color: blue; } background-color: var(--color);
  • Not using DevTools to inspect variables: happens because beginners are unaware, fix by using the Elements tab to inspect and verify variable values

Questions students ask

  • What is the benefit of using CSS variables? CSS variables make it easy to reuse and update values across a website, saving time and reducing errors.
  • How do I know which variables are available in DevTools? In DevTools, the Elements tab shows the CSS variables applied to an element, and the Styles tab shows all declared variables.
  • Can I use CSS variables with other CSS features like media queries? Yes, CSS variables work well with other features like media queries, allowing for more dynamic and responsive designs.

Quick recap: CSS Variables and Custom Properties · Building a Design Token Set · Editing Live to Test a Fix · CSS Variables and Fallback Values · Organising a Stylesheet in a Predictable Order · Debugging with DevTools: The Box Model Panel · CSS Variables · DevTools · Debugging Layout Issues

Next lesson: Your Portfolio Is Your CV.

Learn this with a real instructor

Free lessons take you a long way on your own. The full programmes add live classes, assignments, Skill Points and a certificate — built for African students.