【问题标题】:How to add two css variables and assign it to another variable如何添加两个css变量并将其分配给另一个变量
【发布时间】:2023-01-09 01:57:26
【问题描述】:

我有一个场景,我需要添加值(以像素为单位)并将它们分配给另一个变量并在 CSS 中重用这个新变量。

预期:宽度和高度应分别使用变量值--width--height

但是目前,没有观察到预期的行为。 (运行代码 sn-p 可以看到这个)

.div {
  --a: 200px;
  --b: 100px;
  
  --width: calc(var(--a)+var(--b));
  --height: calc(var(--a)-var(--b));

  width: var(--width);
  height: var(--height);

  background-color: green;
}
<div class="div">Styles are not being applied on me. I need to be more taller and wider according to CSS. </div>

【问题讨论】:

    标签: css css-variables calc


    【解决方案1】:

    看起来问题可能出在 CSS 代码的语法上。

    .div {
      --a: 200px;
      --b: 100px;
      
      --width: calc(var(--a) + var(--b));
      --height: calc(var(--a) - var(--b));
    
      width: var(--width);
      height: var(--height);
    
      background-color: green;
    }
    

    我在“calc()”函数中的“+”和“-”运算符周围添加了空格,以使代码更具可读性。

    这应该允许正确计算“--width”和“--height”变量并将其应用于“.div”元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 2017-03-06
      相关资源
      最近更新 更多