Search code examples
csscss-grid

Dynamically convert em to px inside of css?


I need to know the current em, based on the context, inside of a css style sheet. Is that possible?

I want to calculate the number of pixels for two items: one is in pixels and the other is em:

--item-min-width: 250px;
--gap: 3em; (note: this might be different and is not known until runtime)
--max-number-items: 3;

Now I need the total width of those three items, plus the gap. Something sort of like this (which of course won't work because I can't add pixels (item-min_width) and em (gap)):

@media (min-width: calc(
  var(--max-number-items) * var(--item-min-width) + var(--gap)
))

The goal is to convert the gap (3em) to pixels dynamically. Is it possible to figure out the current em of an element?


Solution

  • You don't need to convert units, calc can handle that:

    calc(100% + 10px)
    calc(2rem - 1%)
    calc(var(some-var) + var(another-var))
    

    https://developer.mozilla.org/en-US/docs/Web/CSS/calc