title: Controlling the specificity of CSS Modules in a Next.js App
body: <p>I'm trying to figure out a good workflow of how to use Tailwind together with CSS Modules in Next.js, but I'm running into some tricky problems regarding specificity and the order in which styles are inserted by Webpack.</p>
  <p>Consider the following use case: I want to create a reusable Button component whose styles can be overridden with utility classes. <strong>Option 1</strong> is to extract the component, as mentioned in the <a href="https://tailwindcss.com/docs/extracting-components" rel="noreferrer">Tailwind Docs</a>:</p>
  <pre class="lang-js prettyprint-override"><code>/* button.jsx */
  
  export const Button = props =&gt; &lt;button {...props} className={`btn {props.className}`} /&gt;
  </code></pre>
  <p>and in my <code>tailwind.css</code> file I'd add the classname in the <code>@layer</code> directive:</p>
  <pre class="lang-css prettyprint-override"><code>@tailwind base;
  @tailwind components;
  @tailwind utilities;
  
  @layer components {
    .btn { @apply ... }
  }
  </code></pre>
  <p>This is nice because I can override any of the buttons styles with utility classes, since they have higher specificity. However, I see a few minor problems here:</p>
  <ul>
  <li>the class is now global, so it's included in every page even if I don't use the component</li>
  <li>the style and component are no longer colocated - this might get messy if I create many such classes</li>
  </ul>
  <p><strong>Option 2</strong> would be to use a CSS Module and apply the classes like this:</p>
  <pre class="lang-css prettyprint-override"><code>/* button.module.css */
  
  .btn { @apply ...}
  </code></pre>
  <pre class="lang-js prettyprint-override"><code>/* button.jsx */
  
  import styles from &quot;./button.module.css&quot;;
  
  export const Button = props =&gt; &lt;button {...props} className={`${styles.btn} {props.className}`} /&gt;
  </code></pre>
  <p>This way the CSS only gets loaded when the component is used, and the styles are colocated. Problem here is that in Next.js CSS Modules are inserted after global CSS, so they have higher specificity. Which totally makes sense, usually I'd want my CSS Modules to be able to override global styles. However, in this case I'd like them to be inserted <em>before</em> my global styles so that I can override them with utility classes.</p>
  <p>I assume this should be possible by adjusting the Webpack config? Does anyone proficient with Webpack know how to achieve this?</p>