Search code examples
cssmicrosoft-edgecss-variables

Edge browser ignores CSS variable


As you can see in this example: https://jsfiddle.net/50mqy8p1/1/ Microsoft Edge ignores display: var(--display-var, block) after a display: none; so the div is not visible. Other browsers show this correct (IE11 works based on the fallback above the var-usage).

Is there any mistake in my code? Or do you know a workaround? Google did not help me here.

<!DOCTYPE html>
<html>
  <head>
    <title>Edge Demo</title>
    <style>
      html, body {
        height: 100%;
      }
      .foo {
        --display-var: flex;
        background: #369;
        height: 100%;
        align-items: center;
        justify-content: center;
      }
      .make-invisible { display: none; }
      .make-visible {
        display: block;
        display: var(--display-var, block);
      }
    </style>
  </head>
  <body>
    <div class="foo make-invisible make-visible">I am here!</div>
  </body>
</html>

As you can see below, it also happens if you use only one class and a media query

<!DOCTYPE html>
<html>
  <head>
    <title>Edge Demo</title>
    <style>
      .foo {
        --display-var: flex;
        display: none;
      }

      @media (min-width: 320px) {
        .foo {
          display: block;
          display: var(--display-var, block);
        }
      }
    </style>
  </head>
  <body>
    <div class="foo">I am here!</div>
  </body>
</html>

What is our use-case, that let us run in this problem: We have a CMS where a content editor can choose when something should be visible or invisible. Then we generate generic visibility/invisibility classes and a generic corresponding small CSS snippet that handles the visibility. But sometimes you don't want an element to be 'block', but for example 'flex'. With this CSS-Vars trick, the design can decide what it wants the element to be as soon as it becomes visible without doing anything else.


Solution

  • It seems like the display: none; attribute of the .make-invisible class confuses Edge.

    I thought updating the specificity of the .make-visible class to something like .foo.make-visible would make the problem go away but even then the issue persists on Edge.

    The simplest solution IMO would be to remove the .make-invisible class from the div element because I don't see a reason why you would need to have both the .make-invisible and .make-visible classes on a single element at the same time.

    Update

    After considering your update I was able to come up with a hack that isn't too ugly. This not only gets around the issue on Edge but also doesn't affect the behavior on Chrome or FF.

    What you will need to do is define the class twice with each property in an individual class like:

        .foo {
          display: block;
        }
        .foo {
          display: var(--display-var, block);
        }
    

    Here's a working version of your demo: https://jsfiddle.net/sbr29yo6/