journalsup
journalsup

Reputation: 130

Passing values from html to tailwind.config.js file? (Css custom properties for tailwind)?

Is it possible to pass a value from html to the tailwind.config.js file?

I essentially want to do something similar to how we can pass a value from HTML to CSS using use custom properties. But instead passing it to the tailwind.config.js file.

For example, with HTML and CSS you can do:

.fill-color {
  color: var(--color);
}

<div class="fill-color" style="--color: blue;">Test</div>

but in my project I need to pass in a variable like: 20 from the index.html file:

<div class="scroll" style="--variable-number: 20">Test</div>

So I can use it to set the keyframes percentage correctly: Tailwind.config.js file below

module.exports = {
  extend: {
     animation: {
         scroll: 'scroll 25s linear infinite'
     }
  },
  keyframes: {
     scroll: {
        '0%': {transform: 'translateX(0%)'},
         '100%': {transform: 'translateX(NEED 20 VALUE HERE%)' },
     }
  },
}

Upvotes: 0

Views: 2736

Answers (2)

Roy Barber
Roy Barber

Reputation: 312

You can achieve this using custom css variable and arbitrary values.

Heres a demo: https://play.tailwindcss.com/qEqKUVP8IQ

Whats happening:

First we define our custom keyframes and animation in the config. allowing it to read a css var like so:

extend: {
  keyframes: {
    scroll: {
      '0%': {transform: 'translateX(0)'},
     '100%': {transform: 'translateX(var(--scroll-distance))' },
    }
  },
  animation: {
    scroll: 'scroll 1s linear infinite'
  },
},

then we can use arbitrary values in our class naming like so:

<div class="animate-scroll [--scroll-distance:20px]">Test</div>
<div class="animate-scroll [--scroll-distance:50px]">Test</div>

So same animation, but a custom distance on multiple elements.

The other option is to define a default value in the css file like so:

:root {--new-variable: red;}

and use it on an element

<div class="bg-[color:var(--new-variable)]">Test</div>

Hope that helps.

Upvotes: 1

Gabe
Gabe

Reputation: 2676

Yes, you can do what you want to achieve, see this playground for a working example. Just add var(--percentage) to the translateX.

HTML:

<div class="animate-text-scroll" style="--percentage: 20%">Test</div>

Tailwind config:

module.exports = {
  theme: {
    extend: {
      keyframes: {
        'scroll': {
          '0%': { transform: 'translateX(0)' },
          '100%': { transform: 'translateX(var(--percentage))' },
        },
      },
      animation: {
        'text-scroll': 'scroll 2s linear infinite',
      },
    },
  },
  plugins: [],
}

Hope this helps.

Upvotes: 2

Related Questions