How to use CSS Variables with Ruby on Rails

March 28, 2022

Track your progress

Sign in to track your progress and access subscription-only lessons.

Log In

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

CSS Variables or CSS custom properties allow you to define variables that can be used throughout your CSS to change properties and their values dynamically. It's a wonderful feature for allowing users to customize the look of your website.

Notes

Resources

Here's an example on how to use it. We've defined --primary-color as a CSS custom property / variable and set it to the Current Account's color. If that is nil, we'll fallback to #000. The h1 tag will use this CSS custom property to set the text color and fallback to blue if the custom property is not defined.

<head>
    <style>
      :root {

        --primary-color: <%= current_account.color || "#000" %>;
      }

      h1 {
        color: var(--primary-color, blue);
      }
    </style>
</head>

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.