【问题标题】:Using CSS how to change only the 2nd column of a table使用 CSS 如何仅更改表格的第二列
【发布时间】:2010-03-29 00:01:26
【问题描述】:

仅使用 css,如何仅覆盖表格第二列的 css。

我可以使用以下方法访问所有列:

.countTable table table td

我无法访问此页面上的 html 来修改它,因为它不是我的网站。

谢谢。

【问题讨论】:

    标签: css


    【解决方案1】:

    您可以像这样使用:nth-child 伪类:

    .countTable table table td:nth-child(2)
    

    但请注意,这在旧版浏览器(或 IE)中不起作用,在这种情况下,您需要为单元格指定一个类或使用 javascript。

    【讨论】:

    • 这只会给出每个表格中的第二个单元格,而不是每行中的第二个单元格。你需要 .countTable table table tr td:nth-child(2)
    • @Deeksy - 这不准确,它不关心选择器是什么。 nth-child 在找到元素后应用,与它所拥有的任何父元素相比,它都是 nth,无论它是否在选择器中。你可以在这里看到这个工作:jsfiddle.net/JQQPz
    • 如何仅更改 td:nth-child(2) 中元素的 css。像 标签。会是 td a:nth-child(2){} 吗?
    • @ivory-santos 只需在末尾添加a,例如td:nth-child(2) a 为该元素下的链接设置样式。
    • 为什么你有两次桌子(不像下面的其他答案)?
    【解决方案2】:

    试试这个:

    .countTable table tr td:first-child + td
    

    您还可以重申以设置其他列的样式:

    .countTable table tr td:first-child + td + td {...} /* third column */
    .countTable table tr td:first-child + td + td + td {...} /* fourth column */
    .countTable table tr td:first-child + td + td + td +td {...} /* fifth column */
    

    【讨论】:

    • 我在维护代码的网站所有者不是开发人员的情况下选择了这个,这使他们能够以非常直接的方式更改数据表中列的对齐方式,虽然有点冗长,但像您在这里的评论一样,让他们很容易知道哪个选择器块用于左侧的哪一列。同样不是最优雅和最有效的方式,但它确实有效!
    【解决方案3】:

    要仅更改表的第二列,请使用以下命令:

    一般情况:

    table td + td{  /* this will go to the 2nd column of a table directly */
    
    background:red
    
    }
    

    您的情况:

    .countTable table table td + td{ 
    
    background: red
    
    }
    

    注意:这适用于所有浏览器(现代和旧的),这就是为什么我将我的答案添加到一个旧问题

    【讨论】:

    • 只选择第一列会有什么调整?使用 table td { ... } 也会选择其他列中的所有单元格。
    • @j4v1 table td { background: red;} // 第一列将有红色背景 table td + td { background: blue;} // 其余的将有蓝色
    【解决方案4】:

    在这个网络上http://quirksmode.org/css/css2/columns.html 我发现了这个简单的方法

    <table>
    <col style="background-color: #6374AB; color: #ffffff" />
    <col span="2" style="background-color: #07B133; color: #ffffff;" />
    <tr>..
    

    【讨论】:

    • 他说他不能修改HTML。
    【解决方案5】:

    您可以为第二列中的每个单元格指定一个类。

    <table>
    <tr><td>Column 1</td><td class="col2">Col 2</td></tr>
    <tr><td>Column 1</td><td class="col2">Col 2</td></tr>
    <tr><td>Column 1</td><td class="col2">Col 2</td></tr>
    <tr><td>Column 1</td><td class="col2">Col 2</td></tr>
    </table>
    

    【讨论】:

    • 我不能用这个。就像我说的,这不是我的页面,所以我不能更改 html。
    • @Duniyadnd 与使用选择器的现有方式相比,这不是一个好方法。
    猜你喜欢
    • 2013-06-30
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多