Skip to main content

Project 1: Building button variations

Idorenyin ObongMarch 20, 2025About 2 minCSSArticle(s)blogblog.logrocket.comcss

Project 1: Building button variations 관련

How to use CSS variables like a pro

Build four simple projects to learn how CSS variables can help you write reusable, elegant code and streamline the way you build websites.

How to use CSS variables like a pro
Build four simple projects to learn how CSS variables can help you write reusable, elegant code and streamline the way you build websites.

In CSS frameworks such as Bootstrap, variables make sharing a base design across elements much easier. Take the .bg-danger class, which turns an element’s background color to red and its own color to white. In this first project, you’ll build something similar.

Get started with the first project by adding the following HTML document to a new .html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>CSS Variables - Button Variations</title>
  </head>
  <body>
    <section>
      <div class="container">
        <h1 class="title">CSS Color Variations</h1>
        <div class="btn-group">
          <button class="btn btn-primary">Primary</button>
          <button class="btn btn-secondary">Secondary</button>
          <button class="btn btn-link">Link</button>
          <button class="btn btn-success">Success</button>
          <button class="btn btn-error">Error</button>
        </div>
      </div>
    </section>
  </body>
</html>

The structure of this markup is pretty standard. Notice how each button element has two classes: the btn class and a second class. We’ll refer to the btn class, in this case, as the base class and the second class as the modifier class that consists of the btn- prefix.

Next, add the following style tag content to the above

The btn class contains the base styles for all the buttons and the variations come in where the individual modifier classes get access to their colors, which are defined at the :root level of the document. This is extremely helpful not just for buttons, but for other elements in your HTML that can inherit the custom properties.

For example, if tomorrow you decide the value for the --error custom property is too dull for a red color, you can easily switch it up to #f00000. Once you do so, voila — all elements using this custom property are updated with a single change!

Here’s what your first project should look like:

Preview Of Project Using Css To Build Button Color Variations
Preview Of Project Using Css To Build Button Color Variations

You can access the complete source code and see a live preview of this project from this CodePen (shalithasuranga).