Any way to synchronize table column widths with HTML + CSS?

前端 未结 9 1323
花落未央
花落未央 2020-12-24 05:05

I have a number of tables with the same columns and it would look a lot nicer if they shared the same column widths. Is such a thing possible? Putting them in the same tab

9条回答
  •  遥遥无期
    2020-12-24 06:01

    To expand on Ken's answer, you can also specify the exact widths in pixels:

    td { width: 250px }
    

    or ems (width of the letter m):

    td { width: 32em }
    

    or ex or pt or whatever (well...actually %, pt, px, em, ex might be it). If you need your columns to be different widths, then the easy way is to give the table cells classes:

    ...
    
    ......

    and assign column widths to the classes:

    td.col1 { width: 48em }
    td.col2 { width: 200px }
    ...
    

    It should be sufficient to assign column widths to the first row in each table. [edit: looks like I've been scooped on that while I was writing]

    You could probably also go crazy with the CSS 2 sibling selector, and write something like

    tr > td:first-child { width:48em } /* first column */
    tr > td:first-child + td { width: 200px } /* second column */
    tr > td:first-child + td + td { width: 5% } /* third column  */
    ...
    

    but if you have more than a few columns, that could get ugly. And if you're using some sort of template system or script to generate these tables, I'm sure it'll be easier/clearer to just put the class="col#" attribute on each cell in your template once.

提交回复
热议问题