表格列,使用 css 设置最小和最大宽度 [英] Table columns, setting both min and max width with css

查看:48
本文介绍了表格列,使用 css 设置最小和最大宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

关于它的工作原理似乎也有一些相互矛盾的答案:

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

我想要以下内容

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>

有没有不用 javascript 的方法来实现这一点(即使用表格限制拉伸列)?

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

下表列出了一些不同 css 设置的实际渲染结果:

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

推荐答案

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

Tables work differently; sometimes counter-intuitively.

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

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

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

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.

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

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>

这篇关于表格列,使用 css 设置最小和最大宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆