Html 表格列,使用 css 设置最小和最大宽度

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

Table columns, setting both min and max width with css

htmlcsshtml-table

提问by Not loved

I would like to have a table which in the columns can stretch but I'm having a little trouble with min and max width in css.

我想要一个表格,它在列中可以拉伸,但我在 css 中的最小和最大宽度方面遇到了一些麻烦。

It also seems that theres some conflicting answers around how this works:

似乎还有一些关于它是如何工作的相互矛盾的答案:

I would like to have the following

我想要以下内容

table{
   width:100%;
}
.a, .b, .c
{
    background-color: red;
}
.a
{
    min-width: 10px;
    max-width: 20px;
}
.b
{
    min-width: 40px;
    max-width: 45px;
}
.c
{
}

<table>
    <tr>
        <td class="a">A</td>
        <td class="b">B</td>
        <td class="c">C</td>
    </tr>
</table>

Is there a way of achieving this without javascript(ie constrained stretching of columns with a table)?

有没有办法在没有 javascript 的情况下实现这一点(即使用表格限制拉伸列)?

below is a table of what actually gets rendered for some different css setups:

下面是一些不同的 css 设置实际渲染的表格:

enter image description here

在此处输入图片说明

回答by Mr Lister

Tables work differently; sometimes counter-intuitively.

表的工作方式不同;有时与直觉相反。

The solution is to use widthon the table cells instead of max-width.

解决方案是width在表格单元格上使用而不是max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

尽管在那种情况下细胞不会缩小到给定宽度以下,但实际上它们会缩小。
对 c 没有限制,如果你给表格的宽度为 70px,a、b 和 c 的宽度将分别为 16、42 和 12 像素。
表格宽度为 400 像素,它们的行为就像您在上面的网格中所说的那样。
只有当您尝试给表格设置太小的尺寸(小于 a.min+b.min+C 的内容)时,它才会失败:那么表格本身将比指定的更宽。

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

我根据您的小提琴制作了一个片段,其中我删除了所有边框和填充以及边框间距,因此您可以更准确地测量宽度。

table {
  width: 70px;
}

table, tbody, tr, td {
  margin: 0;
  padding: 0;
  border: 0;
  border-spacing: 0;
}

.a, .c {
  background-color: red;
}

.b {
  background-color: #F77;
}

.a {
  min-width: 10px;
  width: 20px;
  max-width: 20px;
}

.b {
  min-width: 40px;
  width: 45px;
  max-width: 45px;
}

.c {}
<table>
  <tr>
    <td class="a">A</td>
    <td class="b">B</td>
    <td class="c">C</td>
  </tr>
</table>