Search code examples
javascriptcsspostcss

How can I fix my postcss config so that the ":has" plugin works?


I am using postcss with vue 3 (vite). Here is my config:

package.json

    "postcss-preset-env": "^7.8.3",

postcss.config.js

const postcssPresetEnv = require("postcss-preset-env");

module.exports = {
  plugins: [
    postcssPresetEnv({
      features: {
        "nesting-rules": true,
        "has-pseudo-class": true,
      },
    }),
  ],
};

Nesting is working as expected, so I guess my config is correct

has-pseudo-class is doing nothing on Firefox 107

I know that this isn't working because the following code produces a purple border on Chromium (which natively supports :has), but nothing on Firefox 107:

.draggable:has(div) {
  border: 1px solid purple !important;
}

What am I doing wrong? Have I misunderstood what the plugin does or how to use it?


Solution

  • This was not working because I needed to import and bootstrap the browser polyfill.

    To solve the issue I added the following code to my HTML head

    <script src="https://unpkg.com/css-has-pseudo@4.0.1/dist/browser-global.js"></script>
    <script>cssHasPseudo(document, { hover: true })</script>
    

    Note that you need to match the browser polyfill to the version of postcss-preset-env that you are using.

    Thanks a bunch to the very helpful folks on the postcss discord chan for helping me troubleshoot this.