代码之家  ›  专栏  ›  技术社区  ›  Jimbo

固定表格单元格宽度

  •  152
  • Jimbo  · 技术社区  · 15 年前

    许多人仍然使用表来布局控件、数据等。—其中一个例子是流行的jqgrid。然而,有一些魔法发生了,我似乎无法理解(它的桌子大声呼喊,有多少魔法可能存在?)

    如何设置表的列宽并像jqgrid一样遵守它??如果我尝试复制这个,即使我设置了 <td style='width: 20px'> 一旦其中一个细胞的含量超过20px,细胞就会膨胀!

    有什么想法或见解吗?

    6 回复  |  直到 15 年前
        1
  •  229
  •   Shane Hudson Jørn Schou-Rode    11 年前

    您可以尝试使用 <col> 标记管理所有行的表样式,但需要设置 table-layout:fixed 上的样式 <table> 或者tables css类并设置 overflow 单元格样式

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col

    <table class="fixed">
        <col width="20px" />
        <col width="30px" />
        <col width="40px" />
        <tr>
            <td>text</td>
            <td>text</td>
            <td>text</td>
        </tr>
    </table>
    

    这是你的CSS

    table.fixed { table-layout:fixed; }
    table.fixed td { overflow: hidden; }
    
        2
  •  89
  •   Community Mohan Dere    8 年前

    现在在HTML5/CSS3中,我们可以更好地解决这个问题。在我看来,建议使用这种纯粹的CSS解决方案:

    table.fixed {table-layout:fixed; width:90px;}/*Setting the table width is important!*/
    table.fixed td {overflow:hidden;}/*Hide text outside the cell.*/
    table.fixed td:nth-of-type(1) {width:20px;}/*Setting the width of column 1.*/
    table.fixed td:nth-of-type(2) {width:30px;}/*Setting the width of column 2.*/
    table.fixed td:nth-of-type(3) {width:40px;}/*Setting the width of column 3.*/
    <table class="fixed">
        <tr>
            <td>Veryverylongtext</td>
            <td>Actuallythistextismuchlongeeeeeer</td>
            <td>We should use spaces tooooooooooooo</td>
        </tr>
    </table>

    你得把桌子摆好 width 即使在 haunter's solution . 否则就不起作用了。
    还有一个新的CSS3功能 vsync 建议是: word-break:break-all; . 这也会将其中没有空格的单词拆分为多行。只需这样修改代码:

    table.fixed { table-layout:fixed; width:90px; word-break:break-all;}
    

    最终结果

    Rendered table

        3
  •  12
  •   Bakudan Lovely    12 年前
    table td 
    {
      table-layout:fixed;
      width:20px;
      overflow:hidden;
      word-wrap:break-word;
    }
    
        4
  •  11
  •   Tarik    10 年前

    我有一个长表TD单元,这迫使表到了浏览器的边缘,看起来很难看。我只是希望该列只有固定的大小,并且当它达到指定的宽度时,将其打断。 所以这对我很有效:

    <td><div style='width: 150px;'>Text to break here</div></td>
    

    您不需要为table、tr元素指定任何类型的样式。 您也可以使用溢出:隐藏;如其他答案所建议的那样,但它会导致多余的文本消失。

        5
  •  0
  •   hafichuk    13 年前
    table { 
        table-layout:fixed; width:200px;
    }
    table tr {
        height: 20px;
    }
    

    10x10

        6
  •  -2
  •   xhdix    10 年前
    table
    {
      table-layout:fixed;
    }
    td,th
    {
      width:20px; 
      word-wrap:break-word;
    }
    

    :第一个子项…:n第n个子项(1)或…