[Feature Request/Discussion] @apply with media queries and pseudo selectors
Problem
@apply currently does not work with pseudo selectors and media queries. I can see why that is difficult, but I wonder if it is on the roadmap to support something like that in the future? I'd love it if @apply could make media queries or hover selectors automatically. Maybe it would have to be a Saas/Less only feature because I'm not sure how it would work with raw CSS, but I'm not sure. Thanks for considering, and thanks for making such an awesome lib
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Implement @apply Support for Media Queries and Pseudo Selectors
The current implementation of @apply in Tailwind CSS does not support media queries and pseudo selectors due to the limitations of CSS parsing and the way Tailwind generates utility classes. This restricts users from applying styles conditionally based on viewport size or user interactions, which is a common requirement in responsive design.
Awaiting Verification
Be the first to verify this fix
- 1
Update Tailwind CSS Configuration
Modify the Tailwind CSS configuration to include support for custom media queries and pseudo selectors. This involves extending the theme to allow for new utility classes that can be applied conditionally.
javascriptmodule.exports = { theme: { extend: { screens: { 'hover': {'raw': '(hover: hover)'}, }, }, }, }; - 2
Create Custom Utilities
Define custom utilities in your Tailwind CSS configuration that utilize the new media queries and pseudo selectors. This allows you to apply styles conditionally based on the defined breakpoints or user interactions.
javascriptaddUtilities({ '.hover\:bg-blue-500:hover': { backgroundColor: '#3b82f6', }, '@media (min-width: 768px)': { '.md\:bg-red-500': { backgroundColor: '#ef4444', }, }, }); - 3
Test the Implementation
Create a sample component that utilizes the new utilities to ensure that they work as expected. Check for hover effects and responsiveness across different screen sizes.
html<div class='hover:bg-blue-500 md:bg-red-500'>Test Element</div> - 4
Document the Changes
Update the documentation to reflect the new capabilities of @apply with media queries and pseudo selectors. This will help other developers understand how to use the new features effectively.
markdown### Custom Utilities You can now use @apply with media queries and pseudo selectors like so: ```css @apply hover:bg-blue-500; @apply md:bg-red-500; ```
Validation
To confirm the fix worked, test the component in various browsers and devices to ensure that the hover effects and media query styles are applied correctly. Use browser developer tools to inspect the applied styles and verify that they match the expected behavior.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep