CSS calc()-乘和除法与单位值 [英] CSS calc() - Multiplication and Division with unit-ed values

查看:432
本文介绍了CSS calc()-乘和除法与单位值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用calc()乘以或除以基于单位的值(例如100%,5px等).

Is it possible to use calc() to multiply or divide with unit-based values (like 100%, 5px, etc).

例如,我希望做这样的事情:

For example I was hoping to do something like this:

width: calc(100% * (.7 - 120px / 100%));

希望它解析为类似(假设100%= 500px):

Hoping it resolved to something like (assuming 100% = 500px):

width: calc(500px * (.7 - 120px / 500px));
width: calc(500px * (.7 - .24));
width: calc(500px * .46);
width: calc(230px);

但是,经过一些实验后,我似乎无法将基于单位的值用作除法的分母.

However after some experimenting it looks like I can't have a unit-based value as the denominator for division.

我似乎也无法将两个值(例如5px * 10px5px * 100%)一起使用.

I also don't seem to be able to multiple two values together like 5px * 10px or 5px * 100%.

我知道在100%的情况下不允许这样做,但是在我的用例中,我想知道120px占整个宽度的百分比,然后将其输入到我的计算的其余部分.

I know it doesn't make sense in 100% of the cases to allow this, but in my use-case, I'd like to know what percentage 120px is of the overall width, which I then feed in to the rest of my calculation.

或者,或者如果有人可以找到一种不同的方式来编写它,那也将起作用.我已经绞尽脑汁,什么也没想出来.

Either that, or if someone could figure out a different way to write it, that would work as well. I've racked my brain and couldn't come up with anything.

推荐答案

在CSS calc()除法中-右侧必须为<number>,因此不能将基于单位的值用于此类除法.

In CSS calc() division - the right side must be a <number> therefore unit based values cannot be used in division like this.

还请注意,在乘法运算中,至少一个参数必须是数字.

Also note that in multiplication at least one of the arguments must be a number.

MDN 对此有很好的说明.

如果您想要更好的计算方法,可以使用预处理器(我喜欢 Sass ).该链接将带您进入他们的指南(在该页面上有一个关于运算符的部分).

If you'd like a better way to do calculations you can use a preprocessor (I like Sass). That link will take you to their guides (on that page there's a section about operators).

这篇关于CSS calc()-乘和除法与单位值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆