【问题标题】:Why using SVG in <table> cell forces table to 100% width?为什么在 <table> 单元格中使用 SVG 将表格强制为 100% 宽度?
【发布时间】:2021-06-29 19:21:39
【问题描述】:

我正在构建应该以合理方式显示数据的表格。如果不需要,不要占用 100% 的宽度。

问题是我在一列中使用折线图,当我使用div 构建该图表时效果很好,但是当我使用SVG 时,表格占用 100%(我更喜欢使用 SVG灵活)。

下面是表格应该是什么样子(如果使用div而不是SVG来显示折线图,看起来就是这样):

这就是使用SVG 时表格的外观,占据整个页面宽度

我认为这是因为SVG 试图尽可能多地占用空间并将表格膨胀到 100%。

如何解决?我使用的是表格固定布局和固定百分比列宽。我不知道表格中要显示的数据和表格宽度,表格应该自动确定最佳宽度。

简化示例:

table { table-layout: fixed; max-wdith: 100% }
tr > * { border: 1px solid black; }
svg { display: block; }
<table>
  <tr>
    <th style="width: 50%;">a</th>
    <th style="width: 50%;">b</th>
  </tr>
  
  <tr>
    <td>a</td>
    <td>
      <svg height="1rem" width="100%">
        <rect x="0%" y="25%" width="100%" height="50%" fill="black"/>
      </svg>
    </td>
  </tr>
</table>

附言

解决此问题的一种可能方法是最初隐藏SVG 线图,并让表格在没有SVG 的情况下呈现。然后在大约 1ms 之后,当表格被渲染时,测量表格宽度并使用 JS 显式设置该宽度。然后显示SVG 行,表格将受到之前测量的显式宽度的限制。但也许有更简单的方法?

【问题讨论】:

  • &lt;th style="width=50%;"&gt; 应该是&lt;th style="width: 50%;"&gt;

标签: javascript html css svg


【解决方案1】:

这里有一个技巧来禁用 SVG 对宽度的贡献。您只需设置width:0 并添加min-width:100% 即可再次恢复全宽:

它应该适用于您的真实示例(我已经测试过)

table {
  table-layout: fixed;
  max-wdith: 100%
}

tr>* {
  border: 1px solid black;
}

svg {
  display: block;
  width:0;
  min-width:100%;
}
<table>
  <tr>
    <th style="width:50%;">aaa</th>
    <th style="width:50%;">bbb</th>
  </tr>

  <tr>
    <td>a</td>
    <td>
      <svg height="1rem" >
        <rect x="0%" y="25%" width="100%" height="50%" fill="black"/>
      </svg>
    </td>
  </tr>
</table>

<table>
  <tr>
    <th style="width:50%;">aaa</th>
    <th style="width:50%;">bbbbbbb</th>
  </tr>

  <tr>
    <td>a</td>
    <td>
      <svg height="1rem">
        <rect x="0%" y="25%" width="100%" height="50%" fill="black"/>
      </svg>
    </td>
  </tr>
</table>

相关:How to match width of text to width of dynamically sized image/title?

【讨论】:

  • 谢谢!我怀疑应该有某种方法可以欺骗浏览器正确显示它。 :)
【解决方案2】:

我发现svg 在没有 viewbox 的情况下很挑剔——从内存中运行,svg 默认为高度/宽度 300x150,尽管这可能已经过时。此外,修正了 th 样式中的错字。

不幸的是,下面的代码创建了一个相对大小、按比例调整大小的 svg。

table { table-layout: fixed; max-width: 100% }
tr > * { border: 1px solid black; }
svg { display: block; }
<table>
  <tr>
    <th style="width: 50%;">a</th>
    <th style="width: 50%;">b</th>
  </tr>
  
  <tr>
    <td>a</td>
    <td>
      <svg style="height: auto; width: 100%;" viewbox="0 0 100 10">
        <rect x="0%" y="25%" width="50%" height="50%" fill="black"/>
      </svg>
    </td>
  </tr>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-03
    • 2013-04-26
    • 2023-03-06
    • 2012-08-26
    • 2012-10-24
    • 1970-01-01
    • 2014-06-25
    • 2011-09-17
    相关资源
    最近更新 更多