2

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?

Ted
  • 2,211
  • 2
  • 19
  • 27
  • 1
    You can add pixels and em, you can even add vh units https://codepen.io/anon/pen/EMjOzO https://developer.mozilla.org/en-US/docs/Web/CSS/calc – arieljuod Feb 27 '19 at 19:31
  • 1
    You cannot use CSS variable inside media query, this is the small drawback of the method of your last question – Temani Afif Feb 27 '19 at 19:53
  • @arieljuod Can you post that as an answer please, and I will accept it? – Ted Feb 27 '19 at 20:33

2 Answers2

3

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

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
arieljuod
  • 15,460
  • 2
  • 25
  • 36
  • 1
    you have to note that not all the combination will work, doing `10px + 1` will for example fail because it's invalid. More details here: https://drafts.csswg.org/css-values-3/#calc-type-checking – Temani Afif Feb 27 '19 at 21:21
2

To get the em value in px. Set default font size for the body (browsers have the default font size of 16px).

EM value compound with nesting of elements, refer the MDN docs(link given below).

So, let say you have set the default font size of 16px.

1 em = 16px.

Now you have a gap of 3em. So 3*16px = 48px.

3*250px + 48px = 798px.

Please have a look at this article from MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/font-size#Ems

and this article from w3schools(Set Font Size With Em): https://www.w3schools.com/css/css_font.asp

Srijan
  • 257
  • 1
  • 8
  • Thanks. However, I am actually trying to ask if CSS can get the current em, contextually. I will update my question. – Ted Feb 27 '19 at 18:49
  • I am not able to find anything which can do that. You can get the default font value in JS and convert it into px accordingly. Here is a related question which is using JS for the same. Have a look, https://stackoverflow.com/questions/10463518/converting-em-to-px-in-javascript-and-getting-default-font-size – Srijan Feb 27 '19 at 20:11