英文:
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 -->
<table style="background: green; table-layout: fixed;">
<td style="width: 100px; background: orange;">
<div style="padding: 20%;">
I have % padding
</div>
</td>
<td style="width: 100px; background: orange;">
I have no padding and am really really really really long and stuff
</td>
</table>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论