CSS calc() behaviour in CSS variables

五迷三道 提交于 2020-01-05 04:11:16

问题


I'm curious to the behaviour of using calc() in setting a CSS variable.

Example:

#test {
    --halfWidth: calc(100% / 2);
}

Now, if the #test element, say a div, was 500px wide, I would like the --halfWidth variable to be set to 250px.

But, as far as I can tell the var(--halfWidth) code used elsewhere simply drops in the calc(100% / 2) string instead of 250px. Which means that I can't use the calculation of say element A and use it in element B later on, since it would simply set for example width: var(--halfWidth); as half the width of element B instead of half the width of element A, where the variable was defined.

I've scoured the web trying to find any documentation on the behaviour of this, but I have so far drawn a blank.

Ideally, setting a CSS variable using calc should be available in two variants:

  1. One variant working just like this example, simply dropping in the string as-is, bar any in-string variable replacements.
  2. A second variant where calc() would yield the result of the calculation instead of simply replacing the string.

How to achieve this? I'd rather leave the actual implementation to people suited to it, but one possibility would be an eval() kind of thing; like eval(calc(100% / 2)) would give the result 250px.

Anyway, if anyone have any real documentation on this behaviour or a solution to how to get the example above to yield the result instead, I'm all ears!

Edit: Just FYI, I have read the specs at https://drafts.csswg.org/css-variables/


回答1:


This is kind of a though question to answer cause the answer will not be:

Do it like this...then it will work

The problem you are facing is the normal behavior of CSS. It cascades the styles. If what you are trying to achieve would work it would get real messy after a short amount of time.

I mean how cool is it that you can define a variable like this

#test {
    --halfWidth: calc(100% / 2);
}

where var(--halfWidth) should always be calc(100% / 2). Did you note that it will always be half the width of the parent element?

Imagine how strange it would be if a programmer in a few months reads your code and has box with a width of 1000px set with --halfWidth and now it is 250px wide ... I would think the internet is broken :) It should just be 500px wide.

To achieve what you want, you could/should define different vars defining the widths of the parent elements. And split it down to the children.



来源:https://stackoverflow.com/questions/37385418/css-calc-behaviour-in-css-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!