Menu
Coddy logo textTech

Using CSS Variables

Part of the Practical Frontend section of Coddy's HTML journey — lesson 2 of 35.

CSS variables, also called custom properties, let you save values under a name and reuse them throughout your CSS.
Variables are declared inside a selector (commonly :root so the variable works everywhere on the page, it is called global) using the syntax:

:root {
 --main-color: midnightblue;
 --padding: 16px;
}

To use the value stored in a variable, use the var() function:

.button {
  background-color: var(--main-color);
  padding: var(--padding);
}
challenge icon

Challenge

Easy

You have a webpage showing a few movies playing in the cinema. Each movie has a Buy Ticket button.

Your task:

  1. Create a CSS variable called --main-color inside the :root selector and set its value to seagreen.
  2. Use that variable to set the background color of all <button> elements on the page.

Cheat sheet

CSS variables (custom properties) let you save values under a name and reuse them throughout your CSS.

Variables are declared inside a selector using --variable-name syntax. Use :root to make variables global:

:root {
 --main-color: midnightblue;
 --padding: 16px;
}

To use a variable, use the var() function:

.button {
  background-color: var(--main-color);
  padding: var(--padding);
}

Try it yourself

<html>
<head>
    <title>How to declare a variable</title>
    <style>
        :root {
            --bg-color: #4c87f5;
             /* Write CSS rules here */
             
          }
        body {
            font-family: Arial, sans-serif;
            background: var(--bg-color);
            padding: 20px;
          }
        .movie {
            background: white;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 8px;
          }
        .movie h2 {
            margin: 0 0 10px;
          }
        .movie p {
            margin: 0 0 10px;
          }
        button {
            color: black;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
             /* Write CSS rules here */
            
          }
    </style>
</head>
<body>
    <h1>Today's Movies</h1>
    <div class="movie">
      <h2>Ocean Whispers</h2>
      <p>A sailor discovers a hidden island and the secrets of the sea.</p>
      <button>Buy Ticket</button>
    </div>
    
    <div class="movie">
      <h2>Midnight Chase</h2>
      <p>A detective races against the clock to stop a mysterious heist.</p>
      <button>Buy Ticket</button>
    </div>
    
    <div class="movie">
      <h2>Starlight Bakery</h2>
      <p>A warm comedy about friendship and following your dreams.</p>
      <button>Buy Ticket</button>
</div>
</body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Practical Frontend