【问题标题】:CSS for hiding multiple columns in a table用于隐藏表格中的多个列的 CSS
【发布时间】:2013-12-04 03:21:44
【问题描述】:

我在 SharePoint 网站中有一张类似于下图所示的表格。我无法修改表格,因为它是动态生成的,但我可以添加外部 CSS 来覆盖其样式。我只需要显示第二列并隐藏第一、第三和第四列。

隐藏第一列的伪类是

table#student tr td:first-child { display: none; }

请帮助我使用伪类或任何其他技巧来隐藏第三列和第四列。

<table id="student">
    <tr>
        <td>Role</td>
        <td>Merin</td>
        <td>Nakarmi</td>
        <td>30</td>
    <tr>
        <td>Role</td>
        <td>Tchelen</td>
        <td>Lilian</td>
        <td>22</td>
    </tr>
    <tr>
        <td>Role</td>
        <td>Suraj</td>
        <td>Shrestha</td>
        <td>31</td>
    </tr>
</table>

【问题讨论】:

    标签: html css html-table hide pseudo-class


    【解决方案1】:

    我很惊讶没有人提到通用兄弟选择器。 (More info here) 如果您只需要显示第二列,我会将display: none; 样式应用于第一个单元格和第二个单元格之后的所有单元格。

    table#student td:first-child,
    table#student td:nth-child(2) ~ td {
      display: none;
    }
    <table id="student">
        <tr>
            <td>Role</td>
            <td>Merin</td>
            <td>Nakarmi</td>
            <td>30</td>
        <tr>
            <td>Role</td>
            <td>Tchelen</td>
            <td>Lilian</td>
            <td>22</td>
        </tr>
        <tr>
            <td>Role</td>
            <td>Suraj</td>
            <td>Shrestha</td>
            <td>31</td>
        </tr>
    </table>

    如果出于某种原因需要支持 IE7 和 IE8,可以将 :nth-child() 选择器替换为相邻的兄弟选择器:

    table#student td:first-child,
    table#student td + td ~ td {
      display: none;
    }
    

    【讨论】:

      【解决方案2】:

      CSS3:

      table#student td {
         display: none;
      }
      table#student td:nth-child(2) {
         display: block;
      }
      

      使用nth-child 选择器取消隐藏每行的第二个&lt;td&gt;,有效地显示第二列。

      【讨论】:

      • 这些天,显示:table-cell;更合适。
      • 不幸的是,这打破了使用 colspan 的表格。
      • @Dai 我正好遇到了这个问题和一个解决方案,这里的空间太窄而无法容纳。
      【解决方案3】:

      .hideFullColumn tr > .hidecol
      {
          display:none;
      }

      您可以在表格中使用 .hideFullColumn,在要隐藏的标签中使用 .hidecol。您无需担心 td,因为它们会自动隐藏。

      伪类很好,但是如果你有 50 列并且必须隐藏 20 列,那么你必须重复“td:nth-child(1),td:nth-child(2),.... " 20 次,记住指数。但是在这种情况下,您可以在创建 th 时添加 .hidecol 类,因此您无需修改​​索引。

      你可以试试这个,如果有效,请告诉我。

      【讨论】:

      • 不要使用它,因为它只会隐藏它。
      【解决方案4】:

      您可以使用 CSS3 :nth-child() selector

      td:nth-child(3), td:nth-child(4) {
        display: none
      }
      

      jsfiddle here

      【讨论】:

        【解决方案5】:

        给你。

        CSS:

        table#student tr td:first-child, table#student tr td:nth-child(3), table#student tr td:nth-child(4)  { display: none; }
        

        WORKING DEMO

        【讨论】:

          猜你喜欢
          • 2017-05-04
          • 2016-02-26
          • 1970-01-01
          • 1970-01-01
          • 2019-04-29
          • 1970-01-01
          • 2011-02-20
          • 2022-08-16
          • 2013-03-17
          相关资源
          最近更新 更多