jquery CSS calc() function

匿名 (未验证) 提交于 2019-12-03 07:36:14

问题:

i came across this page CSS LINK i could't help but love the idea of that to calculate the outcome of different units... however i tried this :

$('selector').css({'width':'calc(100%-20px)'}); 

but it doesn't work... anyone has any ideas how this works , or why doesn't this work?

回答1:

jQuery does not support the calc() value, and neither does any of the current browsers.

See a comparison here: http://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28Cascading_Style_Sheets%29

In your example, yo can just use margins on the inner element instead:

<div class="parent"><div class="elem"></div></div>  .parent{     width:100%;     background:green; } .elem{     margin: 0 10px;     background:blue; } 

This way, .elem will be 100% - 20px wide.



回答2:

jQuery supports the calc(). I have used this so many times:

  1. $(".content-section").css('width','calc('+contentSectionWidth+'% - 15px)');

  2. $(".content-section").css('width','calc(100% - 15px)');



回答3:

Some parts of CSS3 are well-supported. Other parts aren't. That's why it has been split into modules, which are in various stages of agreement and implementation. We are a long, long way from even having a complete range of CSS3 specifications, let alone widespread browser support.

So CSS Level 3 Selectors is the most stable specification, having made Recommendation and been implemented by quite a few browsers and other tools (though still, it will take a while for all mainstream browsers to support it well). Several of the other PRs and CRs have enough support in the latest browsers to be of interest.

But “CSS3 Values and Units” is still only an early-stage Working Draft, and is very likely to change significantly before reaching Recommendation. In fact given that no browsers have implemented calc()since the draft was begun years ago, it looks unlikely at this point that this feature will become standard. If you want to stay within the realm of well-supported stuff, you need to stick with CSS 2.1.

In the meantime, saying things like 100%-20px has to be done with nested elements, margins and padding.



回答4:

Ravi verma's answer is correct.

What I would like to add is the reason why your code wasn't working. When doing addition and subtraction with calc, you need to have whitespace preceding and proceeding the operator.

From the MDN docs:

The + and - operators must always be surrounded by whitespace. The operand of calc(50% -8px) for instance will be parsed as a percentage followed by a negative length, an invalid expression, while the operand of calc(50% - 8px) is a percentage followed by a minus sign and a length. Even further, calc(8px + -50%) is treated as a length followed by a plus sign and a negative percentage. The * and / operators do not require whitespace, but adding it for consistency is allowed, and recommended.



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