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%));
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.
I also don't seem to be able to multiple two values together like 5px * 10px
or 5px * 100%
.
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() is a function used for simple calculations to determine CSS property values right in CSS. The calc() function allows mathematical expressions with addition (+), subtraction (-), multiplication (*), and division (/) to be used as component values.
Use div in CSS ArtIn the CSS, select the div with the class attribute, then set an equal height and width for it. You can make a circle with the div tag by coding an empty div in the HTML, setting an equal height and width for it in the CSS, then a border-radius of 50%.
Multiply is a nice and useful one, but there is also: screen , overlay , darken , lighten , color-dodge , color-burn , hard-light , soft-light , difference , exclusion , hue , saturation , color , and luminosity . And also normal which reset it.
A solution for you would be to use CSS calc, it has good browser support and fixes your issue in quite a simple manner. The only downside here is that it doesn't calculate the padding-top in % but you simply cannot calculate padding-top in % from the height of the element unless you use javascript.
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.
The MDN has great documentation on this.
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).
For someone who is making a mistake like me, don't forget that you can't use Sass variables in CSS's calc
function directly. For that, you have to use Sass's calculation method.
$test: 10px; .testing{ width: $test * 2; }
Or if a calc
implementation is necessary:
$test: 10px; .testing{ width: calc(50% + #{$test * 2}); // results in calc(50% - 20px) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With