htmlcss

CSS prefers-color-scheme works on Firefox but not on Chrome issue


My issue is that my prefers-color-scheme styling only works with Firefox and not on Chrome.

Here is a sample of the code. Now I thought this may be an issue to my certain HTML for whatever reason.

@media (prefers-color-scheme: dark) {
  body {
    background-color: red;
  }
}
<!DOCTYPE html>

<body>
  <h1>test</h1>
</body>

</html>

Now I test this in a completely different file and again, it works in Firefox but not Chrome. Does anyone have any reasons why and how I can fix this?


Solution

  • Chrome only offers support for prefers-color-scheme starting with Chrome version 76, which was released July 30th 2019 (5 days ago from the time of this post). Updating your Chrome to the latest version will show your code applying the prefers-color-scheme correctly.

    You can update Chrome by clicking the three dots in the top-right, then help, then About Google Chrome. This will inform you of your current Chrome version, and prompt an automatic update if you do not have the latest version:

    Chrome

    You can check the support for prefers-color-scheme at CanIUse, which shows that Edge, Firefox, Chrome and Safari all support prefers-color-scheme under the latest respective versions:

    Support

    To check whether your browser supports prefers-color-scheme, the following snippet will be red under a dark theme, blue under a light theme, and white if your browser does not support prefers-color-scheme:

    @media (prefers-color-scheme: dark) {
      html {
        background-color: red;
      }
    }
    
    @media (prefers-color-scheme: light) {
      html {
        background-color: blue;
      }
    }

    As in most of the cases the default theme is the light one, only the night theme is defined explicitly. For such cases, the following case won't work unless you use !important in the dark mode:

    @media (prefers-color-scheme: dark) {
      html {
        background-color: red !important;
      }
    }
    
    
    html {
      background-color: blue;
    }