Performance: Creating custom utilities with addUtilities
This affects the CSS bundle size and how quickly styles are applied during page load.
module.exports = {
plugins: [
function({ addUtilities, e, theme, variants }) {
const shadows = theme('boxShadow')
const utilities = Object.entries(shadows).map(([name, value]) => ({
[`.${e(`custom-shadow-${name}`)}`]: { 'box-shadow': value }
}))
addUtilities(utilities, variants('boxShadow'))
}
]
}module.exports = {
plugins: [
function({ addUtilities }) {
addUtilities({
'.custom-shadow': {
'box-shadow': '0 4px 6px rgba(0,0,0,0.1)',
},
'.custom-shadow-lg': {
'box-shadow': '0 10px 15px rgba(0,0,0,0.2)',
},
'.custom-shadow-xl': {
'box-shadow': '0 20px 25px rgba(0,0,0,0.3)',
},
// ... many more similar utilities
})
}
]
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual many custom utilities | No extra DOM nodes | 0 reflows | High paint cost due to large CSS | [X] Bad |
| Dynamic utilities from theme | No extra DOM nodes | 0 reflows | Lower paint cost with smaller CSS | [OK] Good |
addUtilities in Tailwind CSS?addUtilities is used to define new CSS classes with custom styles that Tailwind does not provide by default.addUtilities..text-shadow with text-shadow: 2px 2px #000; using addUtilities?addUtilities expects an object where keys are class selectors and values are objects of CSS properties.addUtilities({
'.custom-border': {
'border-width': '3px',
'border-color': '#f00'
}
}).bg-gradient utility:
addUtilities({
'.bg-gradient': 'background: linear-gradient(to right, #000, #fff);'
}).hover-scale that scales an element to 1.1 times its size on hover using addUtilities. Which is the correct way to add this utility with hover variant support?Pass the test and this pattern moves unknown