Tailwind 4 has been on the horizon for a while, with the team first open-sourcing their progress in March 2024. One of the most noteworthy changes, in my opinion, is the shift from a JavaScript-based configuration to a CSS-based one. Tailwind 4 is currently in beta, and from what I gather, the team is still dealing with some challenges, especially with Safari compatibility.
NOTE: Later in the article, we'll assume you're using a component-based framework / library, but the concepts discussed are easily transferable to other approaches.
Changes in Tailwind 4
The move to a CSS config
I've heard some complaints about this, especially from TypeScript users. However, the roadmap for Tailwind 4.0 does include support for the classic tailwind.config.js as its top priority:
Support for JavaScript configuration files — reintroducing compatibility with the classic tailwind.config.js file to make migrating to v4 easy.
That said, it seems like this is intended primarily for migration purposes and may not be a sustainable long-term solution.
What does this mean for Typesafety
Under the hood Tailwind 4 uses the new @property CSS rules to to define internal custom properties.
We use @property to define our internal custom properties with proper types and constraints
As it stands I'm unable to find decent syntax highlighting support for @property rules in VS code, I have reached out on Bluesky to see if anyone has had more luck than me.
I'm hoping better @property support can aide us in future, more on that later.
What is the @property CSS rule
The @property rule represents a custom property registration directly in a stylesheet without having to run any JavaScript. Valid @property rules result in a registered custom property, which is similar to calling registerProperty() with equivalent parameters.
What are design tokens
Now that we've covered the upcoming changes in Tailwind 4 and their potential impact, let's take a moment to talk about design tokens. If you're not familiar with the term, here's a quick explanation: Design tokens are a method of storing and managing design decisions in a consistent, reusable format, typically as variables. They represent key visual properties of a design system, like colours, typography, spacing, shadows, in a structured way. The goal is to centralise these design values so they can be easily updated, maintained, and shared across different platforms and tools.
Design systems are typically made up of two main types of values: System values and Component values. For example, your system values might look something like this:
const SYSTEM_TOKENS: ISystemTokens = { /* ... */ COLORS: { /* ... */ GREEN: { LIGHT: "#E0E5D9", MEDIUM: "#3F6212", DARK: "#28331A", } /* ... */ }, TYPOGRAPHY: { /* ... */ } /* ... */ }
You can then reference your system values within your component tokens like this:
import { SYSTEM_TOKENS } from "..."; const BUTTON_VALUES: IButtonTokens = { /* ... */ COLORS: { /* ... */ BACKGROUND: SYSTEM_TOKENS.COLORS.GREEN.DARK, /* ... */ }, TYPOGRAPHY: { /* ... */ } /* ... */ }
If you're interested in learning more about design systems, it's worth exploring well-known systems likeMaterial Design.
Structuring component design tokens with Tailwind
About a week ago, I wrote an article discussing an alternative approach I’ve been using for creating component variants with Tailwind CSS. In brief, the article explores how we can leverage CSS variables alongside Tailwind to manage complex variants, setting variant values inline through dynamic component props and variable mapping. If you're curious about how I arrived at this approach, you can read more about it here: A different approach to writing component variants with Tailwind CSS.
We should start by identifying the parts of our component that depend on design tokens. As mentioned earlier, this will include colors, typography, spacing, and any other fixed system values that are integral to your design. Let's take a look at the following Button component, without design tokens:
<button> <p>In the example above, we can pinpoint several values that can be tokenized. Each of the following classes could correspond to a value in our design system:</p> <ul> <li>p-4</li> <li>bg-red</li> <li>text-white</li> </ul> <p>Now that we've identified the values that can be tokenised, we can categorise them into two groups: static values and dynamic values. Static values are those in your component that remain constant, while dynamic values are those that can change based on the props passed to the component. For our example we'll make the padding (p-4) static, while the text colour (text-white) and background (bg-red) should be set dynamically via a theme prop.</p> <h3> Creating the tokens </h3> <h4> Tailwind 4 config </h4> <p>First we need to define our System tokens in the new Tailwind CSS config:<br> </p> <pre class="brush:php;toolbar:false">@import "tailwindcss"; @theme { --color-white: #FFFFFF; --color-green-light: #E0E5D9; --color-green-medium: #3F6212; --color-green-dark: #28331A; --color-red-light: #F4CCCC; --color-red-medium: #D50000; --color-red-dark: #640000; --spacing-sm: 1rem; --spacing-md: 2rem; }
System tokens
Next we need to create our system.tokens.ts file:
export type TColor = "--color-white" | "--color-green-light" | "--color-green-medium" | "--color-green-dark" | "--color-red-light" | "--color-red-medium" | "--color-red-dark"; export type TSpacing = "--spacing-sm" | "--spacing-md"; interface ISystemTokens { COLORS: { WHITE: TColor; GREEN: { LIGHT: TColor; MEDIUM: TColor; DARK: TColor; }, RED: { LIGHT: TColor; MEDIUM: TColor; DARK: TColor; } }, SPACING: { SMALL: TSpacing; MEDIUM: TSpacing; } } export const SYSTEM_TOKENS: ISystemTokens { COLORS: { WHITE: "--color-white"; GREEN: { LIGHT: "--color-green-light"; MEDIUM: "--color-green-light"; DARK: "--color-green-light"; }, RED: { LIGHT: "--color-red-light"; MEDIUM: "--color-red-medium"; DARK: "--color-red-dark"; } }, SPACING: { SMALL: "--spacing-sm"; MEDIUM: "--spacing-md"; } }
System design tokens can be referenced in designs like so:
$system.COLORS.GREEN.LIGHT.
In an ideal world, we could directly export types from our CSS file’s @property rules into our TColor and TSpacing types, much like how SCSS imports can be transformed into JavaScript. Unfortunately, as of now, to the best of my knowledge, this isn't possible.
Component tokens
Now that we’ve implemented our system tokens, we can start integrating them into our components. The first step is to set up our
To recap, here’s how our Button component was structured:
<button> <p>Earlier, we discussed the distinction between static values (like p-4) and dynamic values (like bg-red and text-white). This distinction will guide how we organise our design tokens. Static properties, like p-4, should be grouped under STATIC, while dynamic properties, like bg-red and text-white, should be grouped under the appropriate prop identifier. In this case, since we’re controlling bg-red and text-white through a theme prop, they should be placed under the THEME section in our tokens file. For our example we'll assume 2 theme variables - PRIMARY and SECONDARY.<br> </p> <pre class="brush:php;toolbar:false">import { SYSTEM_TOKENS, TColor, TSpacing } from "./system.tokens.ts"; import { TTheme } from "./Button"; // PRIMARY, SECONDARY interface IButtonStaticTokens { padding: TSpacing; } interface IButtonThemeTokens { backgroundColor: TColor; textColor: TColor; } export const STATIC: IButtonStaticTokens { padding: "--spacing-sm"; } export const THEME: IButtonStaticTokens { PRIMARY: { backgroundColor: "--color-red-dark"; textColor: "--color-red-light"; }, SECONDARY: { backgroundColor: "--color-green-dark"; textColor: "--color-green-light"; }; }
Component design tokens can be referenced in designs like so: $component.Button.THEME.PRIMARY.backgroundColor. My preference for naming conventions is to use:
$component.
$component: Differentiate between $system and $component tokens
PROP_NAME: Constant case
PROP_VALUE: Should follow internal prop value casing
Token name (backgroundColor): Camel case*
This is ultimately a matter of personal preference, and it's up to you to decide what works best for your workflow.
- When naming tokens, I slightly deviate from Camel case if I need to specify a token for an element's state, such as :hover. In those cases, I prefix the token name with the state followed by two underscores, like so: hover__backgroundColor.
Using design tokens in components
As I mentioned earlier in the article, I previously wrote about exploringa different approach to writing component variants with Tailwind CSS. I'll be referencing that approach here, so if you haven't read it yet, it might be helpful to check it out first to understand the context behind this method.
This part of the article will assume you are using a Javascript framework or library to build your components.
Updating the Button component
We need to replace the existing tokenisable classes with Tailwind classes powered by css variables. Note the variable names match those in our 2 Button component token interfaces, IButtonStaticTokens and IButtonThemeTokens;
<button> <p>Now that we've updated our classes, we need to dynamically apply the component styles and update the variables. To achieve this, we'll use a variableMap function on the component. Essentially, this function maps our tokens from Button.tokens.ts to inline CSS variables directly on the component, which our classes can then reference. For an example of a variable map please see the end of this article.<br> </p> <pre class="brush:php;toolbar:false"><template> <button :style="[variableMap(STATIC), variableMap(THEME[props.THEME])]"> <h2> Conclusion </h2> <p>I'm looking forward to the release of Tailwind 4 and what changes the team make between now and then. I've enjoyed experimenting with ideas to deal with some of the challenges around design tokens, variants and typesafety.</p> <p>This is an experimental approach on which I'm sure there will be some strong opinions.</p> <p>If you've found this article interesting or useful, please follow me on Bluesky (I'm most active here), Medium, Dev and/ or Twitter.</p> </button></template>
The above is the detailed content of Exploring Typesafe design tokens in Tailwind 4. For more information, please follow other related articles on the PHP Chinese website!

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools
