All Lessons / How to use CSS Variables with Ruby on Rails

How to use CSS Variables with Ruby on Rails

#439 ยท March 28, 2022

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>

Discussion

Loading...
logo Created with Sketch.

Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

© 2022 GoRails, LLC. All rights reserved.