Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to hide / show table columns by changing the CSS class on the col element only?

Tags:

css

I'm trying to hide / show columns in a table based on users choices during runtime. I defined two CSS classes:

.hide { visibility: collapse; }

.show { visibility: visible; }

I tried to set these styles on the <col> element corresponding to the column I want to hide / show:

<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      ...
    </tr>
  </thead>
  <colgroup>
    <col class="hide">
    <col>
    ...
  </colgroup>
  <tbody>
    <tr>
      <td>Row 1 Column 1</td>
      <td>Row 1 Column 2</td>
    </tr>
    ...
  </tbody>
</table>

However, it only seems to work in Firefox but not in Safari or Chrome. Does Safari and Chrome require special handling? I try to avoid looping through all the rows and modifying the CSS class / style on each corresponding <td>, and the number of columns in the table is large, so I would like to avoid creating one CSS class per column as well. Is there any reliable way to hide / show columns across browsers just by changing the CSS class on <col>?

like image 896
smallbec Avatar asked Aug 06 '10 23:08

smallbec


2 Answers

Webkit based browsers don't seem to support col { visibility: collapse } yet. http://www.quirksmode.org/css/columns.html is quite useful for checking on table column support.

I'm currently playing with:

/* Skipping 1st column: labels */
table.hidecol2 th:nth-child(2),
table.hidecol2 td:nth-child(2),
table.hidecol3 th:nth-child(3),
table.hidecol3 td:nth-child(3) {
  display: none;
}

but then I can afford to not care about IE. Just beware that you're gonna have to tweak for any colspans and rowspans. Use tr:first-child, tr:not(:first-child) etc. etc. to select / avoid as needed.

like image 146
jag Avatar answered Oct 19 '22 02:10

jag


I think the better choice is to use colgroup on your table and modify the css attributes to show or hide a column or a set of columns. For example, you would hide the first five columns like below:

   <table>
        <colgroup>
            <col id="filterTableColgroup" span="5">
        </colgroup>
        <thead>
        <tr>
            <th>...</th>
        </tr> ...

And you would modify the attribute by JQuery like below:

    $("#filterTableColgroup").css('visibility', 'collapse');
like image 31
Youness Avatar answered Oct 19 '22 00:10

Youness