如何在 CSS 中执行算术运算?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16160806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:34:29  来源:igfitidea点击:

How to perform arithmetic operations in CSS?

css

提问by sachinjain024

I want to know how can I achieve an arithmetic operation in CSS.

我想知道如何在 CSS 中实现算术运算。

For example: I want to align two divs side by side each having width of 50% and I want to give border on these divs. I want to write my rule like this.

例如:我想并排对齐两个 div,每个 div 的宽度为 50%,我想在这些 div 上设置边框。我想这样写我的规则。

#container {
    width: 50% - 1px; // I know this does not work.
}

Why do browsers not support such arithmetic operations in CSS ?

为什么浏览器不支持 CSS 中的这种算术运算?

And, How can I get this to work ?

而且,我怎样才能让它发挥作用?

回答by adrift

It already exists; You can use the CSS3 calc()notation:

它已经存在;您可以使用 CSS3calc()表示法:

div {
    background: olive;
    height: 200px;
    width: 200px;
}

div > div {
    background: azure;
    height: calc(100% - 10px);
    width: 100px;
}

http://jsfiddle.net/NejMF/

http://jsfiddle.net/NejMF/

Note: It's only supported in modern browsers(IE9+) and has only recently been adopted by mobile browsers.

注意:它仅在现代浏览器(IE9+) 中受支持,并且最近才被移动浏览器采用。

回答by Ross Allen

Use box-sizing: border-box;on your <div>to make borders part of the width calculation. The default value for box-sizingis content-box, which does not include padding or border in the widthattribute.

使用box-sizing: border-box;你的<div>,让宽度计算的边界部分。默认值box-sizing就是content-box,这还不包括在填充或边框width的属性。

#container {
  border: 1px solid black;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 50%;
}

Paul Irish comments on the use of calc()and suggests using border-boxbecause it better matches our mental model of "width".

Paul Irish 评论calc()建议使用 border-box ,因为它更符合我们对“宽度”的心理模型。

回答by interface

It is possible with a CSS precompiler. LESSans Sassare very popular. You can write it just the way you did it in the example above.

使用 CSS 预编译器是可能的。LESSansSass很受欢迎。您可以按照上面示例中的方式编写它。

http://www.lesscss.org/

http://www.lesscss.org/

LESS is more easy to handle when you are a designer. For programmers and Ruby (on Rails) developers Sass maybe the better choice.

当您是设计师时,LESS 更容易处理。对于程序员和 Ruby (on Rails) 开发人员来说,Sass 可能是更好的选择。