如何自动调整 HTML 表格单元格以适应文本大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5179962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Auto resize HTML table cell to fit the text size
提问by Sonu
I have a table with 2 rows and variable columns. I tried width = 100% for the column. So the first content in the view will fit. But suppose if i am changing the contents dynamically then it is not dynamically increase/decrease the HTML table column size. Thanks in advance.
我有一个包含 2 行和可变列的表。我为该列尝试了宽度 = 100%。所以视图中的第一个内容将适合。但是假设如果我动态更改内容,那么它不会动态增加/减少 HTML 表格列的大小。提前致谢。
回答by Aaron Digulla
If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.
如果您希望单元格根据内容调整大小,则不得为表格、行或单元格指定宽度。
If you don't want word wrap, assign the CSS style white-space: nowrap
to the cells.
如果您不想自动换行,请将 CSS 样式分配给white-space: nowrap
单元格。
回答by Meer
You can try this:
你可以试试这个:
HTML
HTML
<table>
<tr>
<td class="shrink">element1</td>
<td class="shrink">data</td>
<td class="shrink">junk here</td>
<td class="expand">last column</td>
</tr>
<tr>
<td class="shrink">elem</td>
<td class="shrink">more data</td>
<td class="shrink">other stuff</td>
<td class="expand">again, last column</td>
</tr>
<tr>
<td class="shrink">more</td>
<td class="shrink">of </td>
<td class="shrink">these</td>
<td class="expand">rows</td>
</tr>
</table>
CSS
CSS
table {
border: 1px solid green;
border-collapse: collapse;
width:100%;
}
table td {
border: 1px solid green;
}
table td.shrink {
white-space:nowrap
}
table td.expand {
width: 99%
}
回答by vixalien
Well, me also I was struggling with this issue: this is how I solved it: apply table-layout: auto;
to the <table>
element.
嗯,我还我这个问题挣扎:这是我如何解决它:适用table-layout: auto;
于<table>
元素。