【问题标题】:Specifying the width and text alignment of a column指定列的宽度和文本对齐方式
【发布时间】:2011-03-04 04:07:05
【问题描述】:

是否可以使用 css 以百分比形式指定表格列的宽度? 也可以指定特定列的文本对齐方式吗?

例如,我有一个包含 3 列的表。 我想说

col1.width = 20%
col2.width = 40%
col3.width = 40%

col1.text-align = left;
col2.text-align = right;
col3.text-align = center;

【问题讨论】:

    标签: html css


    【解决方案1】:

    关于第一个问题:创建您分配给每个column 的类。比较简单。

    文本的对齐有点困难,因为你只能分配一个few properties to table columns作为一个整体。在这种情况下,一种解决方案是使用 nth-child 伪类,但这是一个 CSS 3 特定功能,在任何当前版本的 Internet Explorer 中都不起作用。正如this answer 建议的那样,您还可以使用+ 组合器来设置相邻列的样式。这是 CSS 2.1 的功能supported by IE >= 7

    <!DOCTYPE html>
    <head>
    <meta charset=UTF-8>
    <title>Column styling</title>
    <style>
    table {
        table-layout: fixed;
        width: 1000px;
    }
    
    .firstColumn {
        width: 20%;
        background: #ccc;
    }
    
    .otherColumns {
        width: 40%;
        background: #eee;
    }
    
    td       { text-align: left }
    td+td    { text-align: right }
    td+td+td { text-align: center }
    </style>
    </head>
    <body>
    <table>
        <col class="firstColumn">
        <col class="otherColumns">
        <col class="otherColumns">
        <tr>
            <td>bla</td>
            <td>bla</td>
            <td>bla</td>
        </tr>
        <tr>
            <td>bla</td>
            <td>bla</td>
            <td>bla</td>
        </tr>
        <tr>
            <td>bla</td>
            <td>bla</td>
            <td>bla</td>
        </tr>
    </table>
    </body>
    </html>
    

    【讨论】:

      【解决方案2】:

      您可以这样做,但此时您的 &lt;td&gt; 宽度是相对于父容器的。

      【讨论】:

      • 我该怎么做呢?我必须给每个 td 元素一个类吗?或者将 tds 包装在 div 中并指定 div 的宽度?哪种方法是正确的?
      猜你喜欢
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 2021-01-16
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      相关资源
      最近更新 更多