Custom utilities let you add your own styles easily. This helps you reuse special styles without writing CSS again and again.
0
0
Creating custom utilities with addUtilities in Tailwind
Introduction
You want a special color or size not in Tailwind by default.
You need a unique style for a project that Tailwind doesn't cover.
You want to keep your HTML clean by using short utility classes.
You want to share custom styles across many pages or components.
You want to add hover or focus styles that Tailwind doesn't provide.
Syntax
Tailwind
addUtilities({
'.your-class': {
'property': 'value',
'property2': 'value2'
},
'.another-class': {
'property': 'value'
}
}, {
variants: ['responsive', 'hover']
})Use addUtilities inside your Tailwind plugin function.
The first argument is an object with class names and CSS properties.
Examples
Adds a
.text-shadow class that applies a red shadow to text.Tailwind
addUtilities({
'.text-shadow': {
'text-shadow': '2px 2px #ff0000'
}
})Adds a
.skew-10deg class that skews an element on hover.Tailwind
addUtilities({
'.skew-10deg': {
'transform': 'skewY(-10deg)'
}
}, {
variants: ['hover']
})Adds a
.border-3 class with 3px border width, usable with responsive prefixes like md:border-3.Tailwind
addUtilities({
'.border-3': {
'border-width': '3px'
}
}, {
variants: ['responsive']
})Sample Program
This example adds two custom utilities: .text-shadow for shadow on text, and .rotate-15 to rotate an element 15 degrees on hover. The button rotates smoothly when hovered.
Tailwind
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Custom Utilities Example</title> <script src="https://cdn.tailwindcss.com"></script> <script> tailwind.config = { plugins: [ function({ addUtilities }) { addUtilities({ '.text-shadow': { 'text-shadow': '2px 2px 4px rgba(0,0,0,0.5)' }, '.rotate-15': { 'transform': 'rotate(15deg)' } }, { variants: ['responsive', 'hover'] }) } ] } </script> </head> <body class="p-6"> <h1 class="text-3xl font-bold text-shadow mb-4">Hello with Shadow</h1> <button class="bg-blue-500 text-white px-4 py-2 rounded hover:rotate-15 transition-transform"> Hover me to rotate </button> </body> </html>
OutputSuccess
Important Notes
Custom utilities work like normal Tailwind classes and can have responsive or state variants.
Always test your custom utilities in different screen sizes to ensure responsiveness.
Use descriptive class names to keep your code easy to read.
Summary
Use addUtilities to create your own Tailwind classes with custom CSS.
Custom utilities help keep your HTML clean and styles reusable.
You can add variants like hover or responsive to your utilities.