@apply doesn't work inside <style jsx></style>
Problem
Hi @adamwathan , I was working on a React component in NextJS and was using Tailwind to customize the designs. Putting the tailwind classes in `className` works fine while using like : [code block] But, since I am using too many classes for the component, and it will be a common style. I wanted to make it work by using @apply into another custom class. Something like : [code block] and CSS goes like : [code block] BTW I am using Styles as JSX. So, finally I want my component to look like : [code block] But this doesn't works out. Error I get is while inspecting the element Can you help me out in understanding if I am doing anything wrong, or does it support working under <style jsx> or not? An alternate solution would be appreciated. Thanks
Error Output
Error I get is while inspecting the element
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Use Tailwind CSS with Styled JSX Correctly
The @apply directive is not supported within <style jsx> tags because styled-jsx does not process Tailwind CSS directives. Instead, Tailwind CSS is designed to work with class names directly in the className attribute. The scoped styles in styled-jsx do not recognize Tailwind's @apply syntax.
Awaiting Verification
Be the first to verify this fix
- 1
Create a Global CSS File
Move your Tailwind CSS styles to a global CSS file instead of using <style jsx>. This allows you to use @apply without issues.
css@tailwind base; @tailwind components; @tailwind utilities; .custom-class { @apply bg-blue-500 text-white p-4 rounded; } - 2
Import Global CSS in _app.js
Ensure you import your global CSS file in your Next.js application. This is typically done in the pages/_app.js file.
javascriptimport '../styles/globals.css'; - 3
Use Custom Class in Component
Replace the inline Tailwind classes in your component with the custom class you defined in your global CSS file.
javascript<div className='custom-class'>Your content here</div> - 4
Remove <style jsx> for Tailwind Classes
Remove any <style jsx> tags that were previously used for Tailwind classes, as they will not work with @apply.
javascript<style jsx>{``}</style>
Validation
Confirm that the styles are applied correctly by inspecting the element in the browser. The custom class should reflect the styles defined in your global CSS file without any errors.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep