在具有 table-layout: fixed 属性的表格内填充百分比。

huangapple go评论67阅读模式
英文:

Padding percentage inside a table with table-layout: fixed

问题

这是在表格单元格内设置百分比内边距而不硬编码单元格宽度的一种方法吗?

我有一个表格,其中列的数量动态变化,每列必须具有相等的宽度,因此我设置了:

table
{ 
   table-layout: fixed; 
}

它运行得很好,但我还想在几个单元格内设置百分比内边距。不幸的是,由于列数不确定,我无法为这些单元格设置特定的宽度。

如果我只是设置:

table tbody tr td.with_padding
{
   padding: 20%;
}    

它看起来像是根据整个表格的宽度计算单元格内的填充,而不是特定单元格的宽度。

如何使用纯CSS解决这个问题,如果可能的话?

英文:

Is this a way to set a percentage padding inside a table cell without hard coding a width of this cell?

I have a table with dynamically changing number of columns, each of which must have an equal width, so I set:

table
{ 
   table-layout: fixed; 
}

It works great, but I also want to set a percentage padding inside several cells. Unfortunately, because of uncertain number of columns, I can't set a particular width to these cells.

If I just set:

table tbody tr td.with_padding
{
   padding: 20%;
}    

it looks like a padding for sells is calculated depending on width of whole table rather than of particular cell.

How can I solve this with pure CSS, if possible?

答案1

得分: 0

是的,%填充将相对于父元素解析,即tr,其宽度将与表格相同。如果您希望%填充相对于单元格的宽度解析,可以在单元格内放置另一个div,并将所有单元格内容放在此内部div中。

<table style="background: green; table-layout: fixed;">
  <td style="width: 100px; background: orange;">
    <div style="padding: 20%;">
      我有%填充
    </div>
  </td>
  <td style="width: 100px; background: orange;">
    我没有填充,而且真的很长很长很长很长
  </td>
</table>
英文:

Yes, the % padding will resolve against the parent element, which is the tr, which will be the same width as the table. If you want the % padding to resolve against the cell's width, you can put another div inside the cell and put all the cell's content in this inner div.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

td {
  vertical-align: top;
}

<!-- language: lang-html -->

&lt;table style=&quot;background: green; table-layout: fixed;&quot;&gt;
  &lt;td style=&quot;width: 100px; background: orange;&quot;&gt;
    &lt;div style=&quot;padding: 20%;&quot;&gt;
      I have % padding
    &lt;/div&gt;
  &lt;/td&gt;
  &lt;td style=&quot;width: 100px; background: orange;&quot;&gt;
    I have no padding and am really really really really long and stuff
  &lt;/td&gt;
&lt;/table&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月18日 17:25:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492371.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定