CSS for hiding multiple columns in a table

不羁的心 提交于 2019-12-19 05:13:43

问题


I have a table similar to the one illustrated below in a SharePoint site. I cannot modify the table as it is generated dynamically but I can add external CSS to override its style. I am required to show only second column and hide first, third and fourth column.

The pseudo class to hide first column is

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

Please help me with pseudo class or any other trick to hide third and forth column.

<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>

回答1:


CSS3:

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

Use nth-child selector to un-hide the 2nd <td> of every row, effectively showing the 2nd column.




回答2:


You can use the CSS3 :nth-child() selector

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

jsfiddle here




回答3:


I'm surprised no one mentioned the general sibling selector. (More info here) If you only need to show second column, I'd apply a display: none; style to the first cell and all cells after the second one.

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>

If you need to support IE7 and IE8 for some reason, you could replace the :nth-child() selector with the adjacent sibling selector:

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



回答4:


Here you go.

The 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




回答5:


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

You can use .hideFullColumn in the table and use .hidecol in the tag which you want to hide. You don't need to worry about td as those will automatically be hidden.

Pseudo class is fine but if you have 50 columns and have to hide 20, then you'd have to repeat the "td:nth-child(1),td:nth-child(2),...." 20 times by keeping the index in mind. But in this case you can add the .hidecol class on creating th, so you don't need to revise index.

You can try this and please let me know if it works.



来源:https://stackoverflow.com/questions/20090764/css-for-hiding-multiple-columns-in-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!