I'm trying to perform a calc()
with two calculations in a nested calc()
, which works in JS (since it renders as a single number), but not inline, so I'm trying to find a workaround. If I remove the subtraction or the multiplication, it works, but I need both.
<div>Hello World</div>
div {
position: absolute;
left: calc( 10% ( 8 - 10 * 0.15px ) );
}
- The
10
value is an Ember computed property.
CodePudding user response:
It's not entirely clear what you mean by "works in JS".
With calc
you cannot subtract/add unit-less numbers nor multiply two numbers that have a unit.
The problem with your code is that first it evaluates:
10 * 0.15px
= 1.5px
But then it tries to do:
8 - 1.5px
with it can't compute because 8 has no unit.
You should do something like:
left: calc( 10% ( 8px - 10px * 0.15 ) );
Or put proper parentheses for precedence:
left: calc( 10% ((8 - 10) * 0.15px ) );
Depends on what you want to achieve (:
CodePudding user response:
You need to use a unit like px
or %
on that 8. When you want it "inline" do you mean hardcoded into the <div>
like so?:
<div style=`left: calc( ${x}% ( 8px - ${y} * 0.15px ))`>Hello World</div>
If so, how do you suppose those variables get a number? The example below uses JavaScript method .setProperty()
to the .style
property of the <div>
thereby an inline style. In DevTools it looks like this:
<div style="position: absolute; left: calc(80% 7.7px);">Hello World</div>
Note, the value is a template literal with the variables interpolated. Is {{var}}
Handlebars? React? IDK the only tag posted is CSS. Also, I left y
without a unit because it'll work with 0.15px
as a valid multiplier.
const div = document.querySelector('div');
let x = 80;
let y = 2;
div.style.setProperty('left', `calc( ${x}% ( 8px - ${y} * 0.15px ))`);
main {
position: relative;
width: 50vw;
min-height: 50vh;
margin: 20px auto;
border: 1px solid #000;
}
<main>
<div style='position:absolute;'>Hello World</div>
</main>