85

I have a table with several groups of columns. The table is larger than my page, so I have a control to show/hide some of these groups to fit on the page. The initial table looks good: all columns are about the same width within a group. But when I hide a group, the columns are not the same width anymore, and it looks bad.

Example: http://www.reviews-web-hosting.com/companies/apollohosting.html (broken link)

So far, the table looks fine. Click on >>. The first column under "Ecommerce Pro" is much wider than the other columns under "Ecommerce Pro", it looks odd. Click on <<, this time the first column under "Value" is too wide. At least on Firefox.

I've tried to use

<colgroup><col /><col span="5" />...

but no luck. If I set a col to style="display: none", the set of columns is still displayed.

Any HTML/CSS tip to keep the columns with the same width withing a group?

Edit:

  • to hide a column, I have to use visibility: collapse
  • it seems to be resizing well now, I do not know why
Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
Julien
  • 5,729
  • 4
  • 37
  • 60

4 Answers4

216

If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your <thead> to <caption> and remove the <td> inside of it, and then set fixed widths for the cells in <tbody>.

Ole Helgesen
  • 3,191
  • 1
  • 18
  • 8
30

give this style to td: width: 1%;

Tone Škoda
  • 1,463
  • 16
  • 20
  • 6
    With an unknown number of columns, this actually does the trick, if the table itself has a fixed width or `width: 100%` – Lars Ebert Mar 17 '17 at 09:56
  • Why does this work? And can I use this trick when I want to have the left column with a fixed width and all others with the same width? – STh Jan 07 '22 at 08:53
0

In your case, since you are only showing 3 columns:

Name    Value       Business
  or
Name    Business    Ecommerce Pro

why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.

scunliffe
  • 62,582
  • 25
  • 126
  • 161
0

well, why don't you (get rid of sidebar and) squeeze the table so it is without show/hide effect? It looks odd to me now. The table is too robust.
Otherwise I think scunliffe's suggestion should do it. Or if you wish, you can just set the exact width of table and set either percentage or pixel width for table cells.

Adriana
  • 8,464
  • 13
  • 36
  • 37