Unlocking the Power of Type-Safe CSS with Vanilla-Extract’s Sprinkles

Why Choose Sprinkles Over Tailwind CSS?

While Tailwind CSS is a powerful tool, it has its limitations. With Sprinkles, you get:

  • Type safety: Enjoy the same type hints and compile-time verification as your TypeScript variables.
  • Customization: Write CSS instead of relying on Tailwind’s shorthand class names, allowing for a more tailored approach.
  • Local scope: Benefit from component-scoped utility classes by default, eliminating style conflicts and making it easier to incorporate multiple design systems within a single app.

Getting Started with Next.js and Vanilla-Extract

To begin, create a new Next.js application and install Vanilla-Extract. You can find the complete source code for this demo project on GitHub.


npm install @vanilla-extract/css @vanilla-extract/next-plugin

After setting up your project, install the necessary dependencies and update your next.config.js file to include the Vanilla-Extract plugin:


module.exports = {
  // ... other configurations ...
  plugins: ['@vanilla-extract/next-plugin'],
};

Creating a Design System with Sprinkles

Sprinkles allows you to define a custom design system from scratch. Start by creating a colors.css.ts file and defining your color values:


import { defineProperties } from '@vanilla-extract/sprinkles';

export const colors = defineProperties({
  color: {
    primary: '#333',
    secondary: '#666',
  },
});

Repeat this process for border, size, and typography styles. Once you’ve set up your design system, define your Sprinkles configuration using the defineProperties function:


import { defineProperties } from '@vanilla-extract/sprinkles';

export const sprinkles = defineProperties({
  // ... other properties ...
  backgroundColor: colors.color,
});

Comparing Sprinkles to Tailwind CSS

One of the key advantages of Sprinkles is its type safety. Try adding a valid CSS property that’s not defined in your Sprinkles configuration, and you’ll receive a type error.

Implementing Themes and Responsive Design

To make your design responsive, add viewport-based conditions to your Sprinkles configuration:


import { defineProperties } from '@vanilla-extract/sprinkles';

export const sprinkles = defineProperties({
  // ... other properties ...
  padding: {
    mobile: '16px',
    tablet: '24px',
    desktop: '32px',
  },
});

Use the property: { condition-name: value } syntax to define responsive styles.

Adding a Dark Theme

To demonstrate how easy it is to toggle between themes, let’s add a dark theme to our product card:


import { defineProperties } from '@vanilla-extract/sprinkles';

export const sprinkles = defineProperties({
  // ... other properties ...
  backgroundColor: {
    light: colors.color.primary,
    dark: colors.color.secondary,
  },
});

Leave a Reply

Your email address will not be published. Required fields are marked *