如何在 LESS CSS 中计算百分比?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8762225/
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-30 02:34:50  来源:igfitidea点击:

How to calculate percentages in LESS CSS?

cssoperatorsless

提问by HappyElephant

I would like to calculate the width of child-container (div etc) in percentages depending on the parent container with LESS CSS.

我想根据具有LESS CSS的父容器以百分比计算子容器(div 等)的宽度。

I am using the forumula by Ethan Marcotte: target / context = result.

我正在使用 Ethan Marcotte 的论坛:target / context = result

Parent container: 620px
Child container: 140px

父容器:620px
子容器:140px

I am using this calculation:

我正在使用这个计算:

div.child-container {
    width: (140/620)*100%;
}

However the output is:

但是输出是:

div.child-container {
    width: 0.2258064516129;
}

I would like to move the decimal point two digits and add the %, like this:

我想将小数点移动两位并添加 %,如下所示:

div.child-container {
    width: 22.58064516129%;
}

Any hints greatly appreciated.

任何提示都非常感谢。

回答by zzzzBov

According to the LESS CSS website, you need to change the order of your equation

根据LESS CSS 网站,您需要更改等式的顺序

The output is pretty much what you expect—LESS understands the difference between colors and units. If a unit is used in an operation, like in:

@var: 1px + 5;

LESS will use that unit for the final output—6pxin this case.

输出几乎是您所期望的——LESS 了解颜色和单位之间的差异。如果在操作中使用了一个单元,例如:

@var: 1px + 5;

LESS 将使用该单位作为最终输出——6px在这种情况下。

It should be:

它应该是:

width: 100%*(140/620);

回答by anddoutoi

Maybe the percentagefunction didn't exist when OP was asking but for future reference I add this answer.

也许percentage当 OP 询问时该功能不存在,但为了将来参考,我添加了这个答案。

div.child-container {
    width: percentage(140/620);
}