【问题标题】:calculation in css variable is not working [duplicate]css变量中的计算不起作用[重复]
【发布时间】:2020-04-13 03:43:06
【问题描述】:

我在 css 中编写了以下代码。第一行的目的是根据屏幕宽度计算一行中可以容纳的对象数量,计算出的数字用于第二行计算这些对象的宽度。

:root{
--linkCount: calc(100vw / 200px);
--linkwidth: calc(230px + (100vw - 60px - (var(--linkCount) * (230px + 6px))) / var(--linkCount));
}

问题是第一个计算calc(100vw / 200px); 不起作用。当我在网站上运行此代码时,对象具有基于内容的最小宽度(所以基本上是width:auto;)当我用例如替换它时calc(5);5; 有效。我已经尝试删除或添加间距,但没有成功。

编辑 1

这里有一个代码 sn-p。这两个变量放在:root https://jsfiddle.net/josvm9dw/

有人可以向我解释为什么它不起作用,因为我不明白。

【问题讨论】:

    标签: css


    【解决方案1】:

    您不能将vw 除以px,它们是不同的计量单位。只除以绝对数:

    --linkCount: calc(100vw / 200);
    

    使用200 或任何你需要的。

    【讨论】:

    • 感谢您的回复,但它不起作用。 calc(800px / 200); 也不能用作测试
    【解决方案2】:

    Docs 当涉及到乘法和除法时,您不需要指定单位,因为它只是不需要

    calc(100vw * 5px) 
    

    为什么px 我们想要的只是将第一个值乘以 5,除法也是如此。

    但是你可以addsubtract 其他单位一起使用。

    演示

    div {
      background: red;
      margin-bottom: 5px;
      height: 50px;
      white-space: nowrap;
      color:white;
    }
    /* At least one must be a number */
    div:nth-child(1) {
      width: calc(100px * 3);
    }
    
    div:nth-child(2) {
      width: calc(100vw * 50vh);
    }
    
    
    /* the right side must be a number */
    div:nth-child(3) {
      width: calc(300px / 2);
    }
    
    div:nth-child(4) {
      width: calc(2 / 200px);
    }
    
    /* both can be units */
    
    div:nth-child(5) {
      width: calc(200px + 3em);
    }
    
    div:nth-child(6) {
      width: calc(100px + 10vh);
    }
    
    div:nth-child(7) {
      width: calc(200px - 20pt);
    }
    
    div:nth-child(8) {
      width: calc(100vw - 50vh);
    }
    <div>calc(100px * 3);</div>
    <div>calc(100vw * 50vh); Invalid treated as auto(default)</div>
    
    <div>calc(300px / 2);</div>
    <div>calc(2 / 200px); Invalid treated as auto(default)</div>
    
    <div>calc(200px + 3em);</div>
    <div>calc(100px + 10vh);</div>
    <div>calc(200px - 20pt);</div>
    <div>calc(100vw - 50vh);</div>

    【讨论】:

    • 感谢您的回复,但它无法正常工作,甚至calc(800px / 200);这应该会导致 4
    • @Vinc199789 你能提供一个重现问题的代码 sn-p 吗?
    • 我在原问题中添加了一段代码
    • 问题是您的第二次计算 --linkwidth: 没有遵循规则,var(--linkCount) 将返回一个以像素为单位的值,如前所述,您不能在乘法中使用单位和分配。从您的第一个 --linkCount: calc(800 / 200); 中解决此问题
    • 这行得通,但我是否可以使用100vw,因为我希望将 800 替换为屏幕宽度。
    猜你喜欢
    • 1970-01-01
    • 2017-01-28
    • 2021-10-22
    • 2019-01-23
    • 2018-06-13
    • 1970-01-01
    • 2018-12-27
    • 2022-01-22
    相关资源
    最近更新 更多