Search code examples
javascripttailwind-cssinlinesveltestring-literals

Change class attribute dynamically inline with tailwind


How do I pass in a dynamic value using a string literal with tailwind inline css?

For example I want to change the width dynamically, and not use tailwinds premade w-1, w-2, etc...

<div
  class="p-1 border-2 width: {createTimeBlock(
    show.startTime,
    show.endTime,
  )}px">
  {show.startTime} to {show.endTime}
</div>

Solution

  • The correct syntax would be w-[{...}px], but Tailwind relies to classes to be statically known, so this will probably not work.

    The easiest thing would probably be to just use style:width="..." or style="width: ...". Though this will have high precedence due to being an inline style.

    Alternatively, you can create a local component class that reads width from a custom property, then set the property using CSS attribute syntax, e.g. style:--width="..." for elements or --width="..." for components, or via the style attribute as style="--width: ...".