Skip to content

Define a @custom-variant dark with media query when in os system dark mode #19330

@vitto

Description

@vitto

What version of Tailwind CSS are you using?

v4.1.17

What build tool (or framework if it abstracts the build tool) are you using?

N/A

What version of Node.js are you using?

N/A

What browser are you using?

Any

What operating system are you using?

Web browser

Reproduction URL

Tailwind Play Link

Describe your issue

Hi, I'm trying to update my media query rules from tailwind 3 to tailwind 4 but It seems it no longer support media queries inside dark mode custom variants.

In Tailwind 3 I've had this config fragment:

...
darkMode: [
    'variant',
    [
      '@media (prefers-color-scheme: dark) { &:is(.pref-theme-system *) }',
      '&:is(.pref-theme-dark *)',
    ],
  ],
...

Now in Tailwind 4 i expect to do that, rules are also changed:

/* user selected dark-mode */

@custom-variant dark (
  &:where(
    .pref-theme-dark
  )
);

/* os system / browser based dark-mode */

@custom-variant dark (
  @media (prefers-color-scheme: dark) {
    &:where(
      .pref-theme-system
    )
  }
);

The problem seems to be that the compiler does not handle properly media queries anymore if I try this simple code on Tailwind Play Link (you have to set os system/browser preferences to dark):

<div class="pref-theme-system">
  <div class="size-10 bg-red-500 dark:bg-green-500"></div>
  <div class="size-10 bg-red-500"></div>
</div>

Result

.dark\:bg-green-500 {
  @media (prefers-color-scheme: dark) {
    &: where( .pref-theme-system * );
  }
   {
    background-color: var(--color-green-500);
  }
}

Expected result:

@media (prefers-color-scheme: dark) {
  .dark\:bg-green-500 {
    &:where( .pref-theme-system * ) {
      background-color: var(--color-green-500);
    }
  }
}

Is there some kind of workaround to obtain browser based dark mode?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions