How to hide columns in HTML table?

后端 未结 9 998
执念已碎
执念已碎 2020-11-27 14:07

I have created a table in ASPX. I want to hide one of the columns based on the requirement but there is no attribute like visible in the HTML table building. Ho

相关标签:
9条回答
  • 2020-11-27 14:35

    You need to use Style Sheet for this purpose.

    <td style="display:none;">
    
    0 讨论(0)
  • 2020-11-27 14:36

    Kos's answer is almost right, but can have damaging side effects. This is more correct:

    #myTable tr td:nth-child(1), #myTable th:nth-child(1) {
        display: none;
    }
    

    CSS (Cascading Style Sheets) will cascade attributes to all of its children. This means that *:nth-child(1) will hide the first td of each tr AND hide the first element of all td children. If any of your td have things like buttons, icons, inputs, or selects, the first one will be hidden (woops!).

    Even if you don't currently have things that will be hidden, image your frustration down the road if you need to add one. Don't punish your future self like that, that's going to be a pain to debug!

    My answer will only hide the first td and th on all tr in #myTable keeping your other elements safe.

    0 讨论(0)
  • 2020-11-27 14:38

    <style>
    .hideFullColumn tr > .hidecol
    {
        display:none;
    }
    </style>

    use .hideFullColumn in table and .hidecol in th.You don't need to add class in td individually as it will be problem because index may not be in mind of each td.

    0 讨论(0)
  • 2020-11-27 14:42

    You can use the nth-child CSS selector to hide a whole column:

    #myTable tr > *:nth-child(2) {
        display: none;
    }
    

    This works under assumption that a cell of column N (be it a th or td) is always the Nth child element of its row.

    Here's a demo.


    ​ If you want the column number to be dynamic, you could do that using querySelectorAll or any framework presenting similar functionality, like jQuery here:

    $('#myTable tr > *:nth-child(2)').hide();
    

    Demo with jQuery

    (The jQuery solution also works on legacy browsers that don't support nth-child).

    0 讨论(0)
  • 2020-11-27 14:43

    you can also use:

    <td style="visibility:hidden;">
    or
    <td style="visibility:collapse;">
    

    The difference between them that "hidden" hides the cell but it holds the space but with "collapse" the space is not held like display:none. This is significant when hidding a whole column or row.

    0 讨论(0)
  • 2020-11-27 14:44

    You can also hide a column using the col element https://developer.mozilla.org/en/docs/Web/HTML/Element/col

    To hide the second column in a table:

    <table>
      <col />
      <col style="visibility:collapse"/>
      <tr><td>visible</td><td>hidden</td></tr>
      <tr><td>visible</td><td>hidden</td></tr>
    

    Known issues: this won't work in Google Chrome. Please vote for the bug at https://bugs.chromium.org/p/chromium/issues/detail?id=174167

    0 讨论(0)
提交回复
热议问题