Html 如何根据内容使表格单元格缩小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11413365/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:33:21  来源:igfitidea点击:

How to make table cell shrink according to the content?

htmlcsshtml-tablewidth

提问by Pavel S.

How can I make the table with 2 columns (cells) look like this:

如何使具有 2 列(单元格)的表格如下所示:

  • First cell is shrink according to the content
  • The other cell fits the rest of the table (wider than both contents together)
  • 第一个单元格根据内容缩小
  • 另一个单元格适合表格的其余部分(比两个内容加在一起都要宽)

Example:

例子:

<table style="width: 500px;">
   <tr>
      <td>foo</td>
      <td>bar</td>
   </tr>
</table>

I need the table to look like this:

我需要表格看起来像这样:

.___________________________________________________________________________.
| foo | bar            <a lot of space here>                                |
|_____|_____________________________________________________________________|
                           500 px total width

Notice: I don't know the width of "foo" so I cannot set "50px", "10%" or something like that.

注意:我不知道“foo”的宽度,所以我不能设置“50px”、“10%”或类似的东西。

采纳答案by scumah

You can set the widthof the second cell to 100%

您可以将width第二个单元格的设置为100%

HTML:

HTML:

<table>
   <tr>
      <td>foo</td>
      <td class="grow">bar</td>
   </tr>
</table>?

CSS:

CSS:

table { width: 500px; }
.grow { width: 100%; }?

Check this fiddleout.

检查这个小提琴

回答by Nat Julian Belza

I know this was asked years ago. The OP probably have solved it by now. But this could still be helpful to someone. So I'm posting what worked for me. Here's what I did with mine. I set the width to anything near zero, to shrink it, then set the white-space to nowrap. Solved.

我知道这是多年前问过的。OP现在可能已经解决了。但这仍然可能对某人有帮助。所以我发布了对我有用的东西。这是我对我所做的。我将宽度设置为接近零的任何值,以缩小它,然后将空白设置为 nowrap。解决了。

td {
width:0.1%;
white-space: nowrap;
} 

回答by Shubham Nigam

Set this:

设置这个:

td {
    max-width:100%;
    white-space:nowrap;
}

This will solve your problem.

这将解决您的问题。

回答by Filipe Manuel

If the total size of the table is 500 pixels and will not pass, put td{max-width: 500px;}; If the minimum value is 500 pixels, td {min-width: 500px;}; Look this exemple.

如果表格的总大小为500像素并且不会通过,则放td{max-width: 500px;}; 如果最小值为 500 像素,则td {min-width: 500px;};看看这个例子