Home > Software engineering >  Modify CSS variable in media query
Modify CSS variable in media query

Time:11-28

Is there a way to modify a previously-declared CSS variable inside a media query with just vanilla CSS? What I'm after would look like this (which of course doesn't work as the variables all get computed in the end):

#container {
  --elem-size: 20px;
}

@media only screen and (min-width: 800px) {
  #container {
    --elem-size: calc(var(--elem-size) * 2);
  }
}

I'm aware that it would be possible to declare a "base variable" (e.g. --base-elem-size) and then modify it for different viewports. However, I'm working with a very large number of CSS variables which makes it undesirable to create a duplicate base set out of them. The ideal solution would be able to "modify" a previously-declared value.

CodePudding user response:

This might be far from ideal but to some degrees does define the style in one line. It uses fallback values of CSS variables.

Open full screen and change window size to see the result:

:root {
  --elem-size-base: 50px;
}

#container {
  /*            
  • Related