Fred Hors
Fred Hors

Reputation: 4136

Nested syntax with PostCSS for :hover and :focus

I'm using TailwindCSS and PostCSS and I have this css code:

.btn {
  @apply py-1;
  @apply px-4;
  @apply border;
  @apply rounded;
}

.btn:hover {
  @apply bg-white text-black;
}

.btn:focus {
  @apply bg-black text-white;
}

Is there a native way in PostCSS (or with a plugin) to write this code like the below?

.btn {
  @apply py-1;
  @apply px-4;
  @apply border;
  @apply rounded;

  &:hover {
    @apply bg-white text-black;
  }
  
  &:focus {
    @apply bg-black text-white;
  }
}

Upvotes: 3

Views: 5883

Answers (3)

Michael Brenndoerfer
Michael Brenndoerfer

Reputation: 4066

Works too, following the object notation Reference

module.exports = {
    plugins: {
        'postcss-import': {},
        tailwindcss: {},
        autoprefixer: {},
        'postcss-preset-env': { stage: 2 },
    },
}

Upvotes: 0

xoryves
xoryves

Reputation: 1466

You could also use postcss-nested plugin.

In your package.json:

{
  "dependencies": {
    "postcss": "^8.2.9",
    "tailwindcss": "^2.0.4",
    "postcss-nested": "^5.0.5"
  }
}

In your postcss.config.js:

module.exports = {
  plugins: [
    require('postcss-nested'),
    require('tailwindcss'),
  ]
}

Upvotes: 0

frouo
frouo

Reputation: 5223

Use postcss-preset-env.

First install, npm install postcss-preset-env --save-dev.

Then enable nesting-rules in your postcss.config.js file,

module.exports = {
  plugins: [
    "tailwindcss",
    [
      "postcss-preset-env",
      {
        stage: 3,
        features: {
          "nesting-rules": true,
        },
      },
    ],
  ],
};

Here you can find the list of features ID that can be enabled

Upvotes: 2

Related Questions