How can I get a negative value of a CSS variables in a calc() expression?

醉酒当歌 提交于 2019-11-26 14:44:03

问题


Let me start by showing you how I would do this in SCSS:

$submenu-padding-left: 1.5em;

transform: translateX(calc(-#{$submenu-padding-left} + .5em));

which would compile to:

transform: translateX(calc(-1.5em - .5em))

Basically SCSS allows me to concatenate a minus symbol - with a variable in order to convert it to a negative value.

Is it possible to achieve this with CSS Variables?


回答1:


Yes you can do it. Simply multiply by -1:

:root {
  --margin: 50px;
}

body {
  margin: 0 100px;
  border:1px solid;
}

.box-1 {
  background: red;
  height: 100px;
  width: 200px;
  margin-left: calc(-1 * var(--margin));
}

.box-2 {
  background: green;
  height: 100px;
  width: 200px;
  margin-left: calc(-1 * (-1 * var(--margin))); /* You can also nest calculation */
}
<div class="box-1">
</div>
<div class="box-2">
</div>


来源:https://stackoverflow.com/questions/48639882/how-can-i-get-a-negative-value-of-a-css-variables-in-a-calc-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!