Html 如何使表格单元格缩小宽度以仅适合其内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14084221/
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 make a table cell shrink width to fit only its contents?
提问by thelolcat
I want the table to have 100% width, but only one column from it should have a free width, like:
我希望表格具有 100% 的宽度,但其中只有一列应该具有自由宽度,例如:
| A | B | C |
so the width of A and B columns should match the width of their contents, but the width of C should go on until the table ends.
所以 A 和 B 列的宽度应该与其内容的宽度相匹配,但 C 的宽度应该一直持续到表格结束。
Ok I could specify the width of of A and B in pixels, but the problem is that the width of the contents of these columns is not fixed, so if I set a fixed width it wouldn't match the contents perfectly :(
好的,我可以以像素为单位指定 A 和 B 的宽度,但问题是这些列的内容的宽度不是固定的,所以如果我设置了固定的宽度,它就不会完全匹配内容:(
PS: I'm not using actual table items, but a DL list wrapped in a div. The div has display:table, dl has display:table-row, and dt/dd display:table-cell ...
PS:我没有使用实际的表格项目,而是使用 div 包裹的 DL 列表。div 有 display:table,dl 有 display:table-row,和 dt/dd display:table-cell ...
回答by Roimer
If I understood you, you have tabular data but you want to present it in the browser using div
elements (AFAIK tables and divs with display:table behaves mostly the same).
如果我理解你,你有表格数据,但你想使用div
元素在浏览器中显示它(AFAIK 表格和带有 display:table 的 div 的行为大致相同)。
(here is a working jsfiddle: http://jsfiddle.net/roimergarcia/CWKRA/)
(这是一个有效的 jsfiddle:http: //jsfiddle.net/roimergarcia/CWKRA/)
The markup:
标记:
<div class='theTable'>
<div class='theRow'>
<div class='theCell' >first</div>
<div class='theCell' >test</div>
<div class='theCell bigCell'>this is long</div>
</div>
<div class='theRow'>
<div class='theCell'>2nd</div>
<div class='theCell'>more test</div>
<div class='theCell'>it is still long</div>
</div>
</div>?
And the CSS:
和 CSS:
.theTable{
display:table;
width:95%; /* or whatever width for your table*/
}
.theRow{display:table-row}
.theCell{
display:table-cell;
padding: 0px 2px; /* just some padding, if needed*/
white-space: pre; /* this will avoid line breaks*/
}
.bigCell{
width:100%; /* this will shrink other cells */
}?
The sad part is I couldn't do this one year ago, when I really needed it -_-!
可悲的是一年前我无法做到这一点,当时我真的需要它-_-!