Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to override the value of a CSS variable inside a container query

At the :root level a CSS variable is declared with a value. This variable is used to style elements.

Inside a container query a new value is assigned to the variable. The styled elements should change to reflect that new value.

This code should change the width of a box when the html element is 40 characters wide. It contains a container query, which does not work, and a media query that does:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

:root {
  --box-w: 10ch;
}

html {
  container: html / size;
}

.box {
  background-color: #fc3;
  height: 3ex;
  width: var(--box-w);
}

@container html (min-width: 40ch) {
   :root {
    --box-w: 30ch;
  }
  .box {
    border: 1ch dotted #c00;
  }
}

@media (min-width: 50ch) {
   :root {
    --box-w: 40ch;
  }
  .box {
    border: 1ch solid #0c0;
  }
}
<div class="box"></div>

The box should be 30 characters wide when the screen is 40 characters wide. That does not happen. The rule is applied since the border changes to red dots, so I think the condition is correct.

The similar syntax does work with a media query.

The media query cannot be used because it uses the default browser font and size, not the actual font and its size set with CSS.

>Solution :

Try this:

@container html (min-width: 40ch) {
    * {
        --box-w: 30ch;
    }

    .box {
        border: 1ch dotted #c00;
    }
}

I believe it does not work, because you are targeting :root with html.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading