csscss-variablescss-calc

CSS: How to use var() inside calc() inside @media


On a website, I have a changing number of buttons (<li>), which I need to resize if they don't fit in a row on mobile devices. Mobile devices have different widths and (as stated before) the number of buttons may vary.

I already have the number of buttons as style parameter in the parent (<ul>) element: style="--buttonCount: 6;" for example. Formatting the buttons now is pretty easy using var() inside calc() in CSS: margin: 0 calc((((100vw - 8px) - (var(--buttonCount) * 40px)) / (var(--buttonCount) - 1))) 0 0; This shows up to be no problem at all, tested in Vivaldi (Chrome) and Firefox on Windows 10.

But this uses and leaves 40px as the button width, which may be too much on smaller screens (10 * 40px = 400px, my Huawei has 360px width). And so I tried to use a Media Query which respects the number of buttons. Using calc() inside a media query isn't a problem, it works very well, but just with fixed numbers: @media (max-width: calc((6 * 40px) + ((6 - 1) * 2px))) {} But I need it to automatically respect the real number of buttons, which I have in the var(--buttonCount). Changing the Media Query to @media (max-width: calc((var(--buttonCount) * 40px) + ((var(--buttonCount) - 1) * 2px))) {} makes it non functional though.

Am I missing something or doing anything wrong here? Can this be done anyway without using JS?

Thanks in advance!


Solution

  • Conclusions of my investigations:

    Using min() I was able to avoid the Media Queries. My problem was, that I wanted the buttons to be 40px by 40px, except when the device width wasn't enough to show them all in one line. min() returns the smallest of 2 values, which - in my case - is the smallest of the calculated possible width and 40px. This way the size is restricted to 40px. Using min() in calculating the right margin as well correctly calculates the space in between of the buttons too.

    https://codepen.io/XM624/pen/GRQVWJx