【问题标题】:Avoid <colgroup> / <col> HTML tags to alter <thead> and <tfoot> rows?避免使用 <colgroup> / <col> HTML 标记来更改 <thead> 和 <tfoot> 行?
【发布时间】:2012-04-30 12:53:45
【问题描述】:

有没有办法限制/约束&lt;colgroup&gt;/&lt;col&gt; HTML 标签中定义的样式的“操作”字段。

给定下表:

<table>
    <colgroup>
        <col align="center" />
        <col align="center" style="background-color: lightgrey;" />
        <col align="center" />
    </colgroup>
    <thead>
        <tr>
            <th>Column A</th>
            <th>Column B</th>
            <th>Column C</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1.a</td>
            <td>1.b</td>
            <td>1.c</td>
        </tr>
        <tr>
            <td>2.a</td>
            <td>2.b</td>
            <td>2.c</td>
        </tr>
    </tbody>
</table>

我希望background-color: lightgrey; 不应用于“B 列”单元格(thead 中的第二个th)。

【问题讨论】:

    标签: html css colgroup


    【解决方案1】:

    您始终可以特别为该单元格应用样式,或为您的标题行设置整个 &lt;tr&gt; 的样式。

    http://jsfiddle.net/QQ7LJ/

     <tr style="background-color:white;">
            <th>Column A</th>
            <th>Column B</th>
            <th>Column C</th>
     </tr>
    

    简而言之:不,没有办法“限制”css,它将匹配每个可用的目标,并且您的 &lt;col&gt; 样式将匹配整个列。为了获得不同的样式,您需要以某种方式覆盖它,最简单的方法是显式设置与一般样式不匹配的样式。

    编辑,您也可以在样式表块中执行此操作,方法是使用 CSS3 选择器 :nth-of-type 并将选择器范围限定为 &lt;tbody&gt; 元素。

    http://jsfiddle.net/QQ7LJ/1/

    tbody td:nth-of-type(2) {
     background-color: lightgrey;   
    }​
    

    以及对 HTML 的更改(其他一切都相同)

    <colgroup>
        <col align="center" />
        <col align="center"/>
        <col align="center" />
    </colgroup>
    

    【讨论】:

    • 我希望有办法限制&lt;col&gt;,但感谢您的回答。覆盖background-color CSS 指令的问题在于,在&lt;td&gt; 上将其设置为transparent 对最终渲染没有影响,因为&lt;col&gt; 似乎就在&lt;td&gt; 的下方。
    • :nth-of-type 确实是一个很好的实用解决方案(至少在我的情况下)。
    • 你应该使用 colgroup 来处理不规则的标题。这是一个不规则的标题?你有一个 3 列的 colgroup,然后每个 tbody tr 都是 3 个 td。这是正常的。请参阅:w3.org/WAI/tutorials/tables/irregular 以获取具有不规则标题的表格示例。
    猜你喜欢
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    相关资源
    最近更新 更多