【问题标题】:CSS - Use calc() to keep widths of elements the sameCSS - 使用 calc() 保持元素的宽度相同
【发布时间】:2014-05-29 09:13:33
【问题描述】:

这样的事情在 CSS 中可能吗?

<table>
  <tr>
    <td id="elementOne">elementOne</td>
    <td id="elementtwo">elementtwo</td>
  </tr>
</table>

<div style="width: calc(document.getElementById(elementOne).width)"></div>

这样 div 的宽度总是与elementOne 相同。

CSS中是否有这样的功能,使用calc()或其他方式?

【问题讨论】:

  • 不,没有这样的功能(在 IE 直到版本 7 中已支持类似的 AFAIK 功能),但您有一个更强大的功能:JavaScript。
  • 这在 IE 中被称为 expression(),这是一个坏主意:stackoverflow.com/questions/527861/…

标签: html css calc


【解决方案1】:

不,使用 CSS 是不可能的。

为此,您必须使用 JavaScript(document.getElementById(elementOne).offsetWidth 或类似名称,具体取决于您要查找的宽度)。 Calc 是 used 进行数学运算,而不是执行脚本。没有办法将 JS 放入 CSS 语句中,就像您尝试做的那样。

有关 JS 位的更多帮助,请参阅How do I retrieve an HTML element's actual width and height?

编辑:有关为什么在 CSS 中实现这将是一个坏主意的一些背景知识,请参阅 Value calculation for CSS(TL;DR:它已被尝试过。事情爆炸了)

【讨论】:

    【解决方案2】:

    使用 CSS 变量:

    <style>
    :root { --width: 100px; } /* Set the variable --width */
    
    table td{
      width: var(--width);    /* use it to set the width of TD elements */
      border: 1px solid;
    }
    </style>
    
    <table>
      <tr>
        <td class="tab">elementOne</td>
        <td class="tab">elementtwo</td>
      </tr>
    </table>
    
    <!-- reuse the variable to set the width of the DIV element -->
    <div style="width: var(--width); border: 1px solid;">Element three</div>
    

    你也可以在 calc() 函数中使用变量:

    <div style="width: calc(var(--width) * 3); border: 1px solid;">Element four</div>
    

    【讨论】:

    【解决方案3】:

    是的。使用 CSS 有两种可能的方法(虽然不是使用 calc):

    1) 如果您知道您有多少列,则只需使用 %(即 50% 表示 2 个列)

    2) 如果您不知道您有多少列,或者您可能无法将 % 用于您可能拥有的任何用例,那么您可以使用flexbox。 根据您的浏览器兼容性目标,您可以结合“旧”和“新”语法来获得一些很棒的结果。

    【讨论】:

      猜你喜欢
      • 2013-03-05
      • 2017-09-28
      • 2014-06-07
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      相关资源
      最近更新 更多