有什么方法可以将表格列宽与 HTML + CSS 同步?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/456859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:01:42  来源:igfitidea点击:

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

htmlcss

提问by cletus

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 table with some rows with no borders between them isn't an option.

我有许多具有相同列的表,如果它们共享相同的列宽,它看起来会好很多。这样的事情可能吗?将它们放在同一个表中,其中一些行之间没有边界,这不是一种选择。

Edit:Yeah I'm aware I can fix the widths myself but I was hoping for something that would tie in to the browser's column width algorithm but simply tied two or more tables together for the purpose of doing that layout.

编辑:是的,我知道我可以自己修复宽度,但我希望有一些可以与浏览器的列宽算法相关联的东西,但只是为了进行布局而将两个或多个表格绑定在一起。

I didn't think such a thing was possible but I thought I'd check just in case.

我不认为这样的事情是可能的,但我想我会检查以防万一。

采纳答案by Ken Browning

It's only possible if you can fix-width the columns. If you can set a fixed width then some css like this should work:

只有当您可以固定列宽时才有可能。如果您可以设置固定宽度,那么像这样的一些 css 应该可以工作:

td {
    width: 25%;
}

You can customize each columns width like this:

您可以像这样自定义每个列的宽度:

<table>
  <tr>
    <td class="col1">...</td>
    <td class="col2">...</td>
  </tr>
</table>
...
<table>
  <tr>
    <td class="col1">...</td>
    <td class="col2">...</td>
  </tr>
</table>

and then specify the widths like this:

然后像这样指定宽度:

.col1 {
   width: 25%;
}
.col2 {
   width: 75%;
}

回答by mercator

If you're not too picky about which column widths the browser comes up with, as long as they're the same across different tables, you can use the CSS table-layoutproperty (supported by all major browsers) in combination with a table width:

如果您对浏览器提供的列宽不太挑剔,只要它们在不同的表格中相同,您可以将 CSStable-layout属性(所有主要浏览器都支持)与表格宽度结合使用:

table {
    table-layout: fixed;
    width: 100%;
}

This causes all columns (without a specified width) to have the same width, regardless of the table content.

这会导致所有列(没有指定宽度)具有相同的宽度,而不管表格内容如何。

回答by Ole Helgesen

Here's a small JavaScript I made to resize cells to make them equal width in all tables on a page.

这是我用来调整单元格大小以使它们在页面上的所有表格中的宽度相等的一个小的 JavaScript。

function resizeTables()
{
    var tableArr = document.getElementsByTagName('table');
    var cellWidths = new Array();

    // get widest
    for(i = 0; i < tableArr.length; i++)
    {
        for(j = 0; j < tableArr[i].rows[0].cells.length; j++)
        {
           var cell = tableArr[i].rows[0].cells[j];

           if(!cellWidths[j] || cellWidths[j] < cell.clientWidth)
                cellWidths[j] = cell.clientWidth;
        }
    }

    // set all columns to the widest width found
    for(i = 0; i < tableArr.length; i++)
    {
        for(j = 0; j < tableArr[i].rows[0].cells.length; j++)
        {
            tableArr[i].rows[0].cells[j].style.width = cellWidths[j]+'px';
        }
    }
}

window.onload = resizeTables;

回答by David Z

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

要扩展 Ken 的答案,您还可以指定以像素为单位的确切宽度:

td { width: 250px }

or ems (width of the letter m):

或 ems(字母 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:

或 ex 或 pt 或其他(嗯……实际上 %, pt, px, em, ex 可能就是它)。如果您需要不同宽度的列,那么简单的方法是给表格单元格类:

<table><tr>
    <td class="col1">...</td><td class="col2">...</td>...
</tr></table>

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

你也可以对 CSS 2 兄弟选择器发疯,写一些类似的东西

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.

但是如果您有多个列,那可能会变得很难看。如果您使用某种模板系统或脚本来生成这些表,我相信只需将 class="col#" 属性放在模板中的每个单元格上一次会更容易/更清晰。

回答by Knut Hamang

Luis Siquot answer is the one I used. However instead of using clientWidth, you should use jquery width() function to normalize widths between browsers, and to not calculate padding. Using clientWidth would result in the table cells expanding on ajaxpostbacks because of the padding (if padding used in the TD's). So, correct code using Luis Siquot's answer would be to replace

Luis Siquot 的答案是我使用的答案。但是,您应该使用 jquery width() 函数来规范浏览器之间的宽度,而不是使用 clientWidth,而不是计算填充。由于填充(如果在 TD 中使用了填充),使用 clientWidth 会导致表格单元格在 ajaxpostbacks 上扩展。因此,使用 Luis Siquot 的答案的正确代码是替换

var cell = $(this)[0].rows[0].cells[j];
       if(!cellWidths[j] || cellWidths[j] < cell.clientWidth) cellWidths[j] = cell.clientWidth;

with

var cell = $($(this)[0].rows[0].cells[j]);
            if (!cellWidths[j] || cellWidths[j] < cell.width()) cellWidths[j] = cell.width();   

回答by Stefanvds

The easiest way is kind of a 'dirty' way, but it works the best. It does exactly what's required:

最简单的方法是一种“肮脏”的方法,但效果最好。它完全符合要求:

Just merge your two tables into one table. In my case the only thing between the two tables was an h3

只需将您的两张表合并为一张表。就我而言,两张桌子之间唯一的东西是h3

So my table

所以我的桌子

<table>
<tr></tr>
<table>

<h3>Title<h3>

<table>
<tr></tr>
<table>

became this:

变成了这个:

<table>
<tr></tr>

<tr><td colspan="6">
<h3>Title<h3>
</td></tr>

<tr></tr>
<table>

this way your table will 'sync' it's size up. of course this only works when there isn't too much complex stuff in between the two tables, but I'm guessing in most cases it isn't. if it was, the sync wouldn't be needed in the first place.

这样你的桌子就会“同步”它的大小。当然,这只适用于两个表之间没有太多复杂内容的情况,但我猜在大多数情况下不是。如果是这样,首先就不需要同步。

回答by Robert K

I'm almost shocked that no one has suggested column groups! With it you can give a column a specific class, width, and other helpful properties. And since it's HTML 4.01 it's supported by all browsers that support the doctype.

我几乎震惊了没有人建议列组!使用它,您可以为列指定特定的类、宽度和其他有用的属性。由于它是 HTML 4.01,所有支持 doctype 的浏览器都支持它。

回答by Luis Siquot

each pair of tables resize its columns to the same width
similar to Ole J. Helgesenbut with jquery and a parameter in order to select which tables equalize.
(I cant vote but it's essentially your solution)

每对表将其列调整为
Ole J. Helgesen相似的相同宽度,但使用 jquery 和一个参数来选择哪些表均衡。
(我不能投票,但它本质上是你的解决方案)

<table data-ss="1" border="1">
  <tr><td>asdf<td>129292<td>text
</table>
<table data-ss="1" border=1>
  <tr><td>a<td>1<td>each column here has the same size than the table above
</table>
<table data-ss="2" border=1>
  <tr><td>asdf<td>129292<td>text
</table>
<table data-ss="2" border=1>
  <tr><td>each column here has the same size than the table above<td>a<td>1
</table>

and use this sctipt

并使用此脚本

$(function(){
  resizeTables('1');
  resizeTables('2');
});

//please set table html attribute `data-ss="something"` to properly call this js
// ss is short for SharedSize
function resizeTables(sharedSize){
  var tableArr = $('table[data-ss='+sharedSize+']');
  var cellWidths = new Array();
  $(tableArr).each(function() {
    for(j = 0; j < $(this)[0].rows[0].cells.length; j++){
       var cell = $(this)[0].rows[0].cells[j];
       if(!cellWidths[j] || cellWidths[j] < cell.clientWidth) cellWidths[j] = cell.clientWidth;
    }
  });
  $(tableArr).each(function() {
    for(j = 0; j < $(this)[0].rows[0].cells.length; j++){
        $(this)[0].rows[0].cells[j].style.width = cellWidths[j]+'px';
    }
  });
}

回答by CletusW

You can sync the column widths by combining the tables (as suggested by @Stefanvds), but using a tbody+ thfor each:

您可以通过组合表格来同步列宽(如@Stefanvds 所建议的那样),但对每个表格使用tbody+ th

table {
  border-collapse: collapse;
}

table thead,
table tbody {
  border-bottom: solid;
}

table tbody th {
  text-align: left;
}
<table>
  <thead>
    <tr> <th> ID <th> Measurement <th> Average <th> Maximum
  <tbody>
    <tr> <td> <th scope=rowgroup> Cats <td> <td>
    <tr> <td> 93 <th scope=row> Legs <td> 3.5 <td> 4
    <tr> <td> 10 <th scope=row> Tails <td> 1 <td> 1
  <tbody>
    <tr> <td> <th scope=rowgroup> English speakers <td> <td>
    <tr> <td> 32 <th scope=row> Legs <td> 2.67 <td> 4
    <tr> <td> 35 <th scope=row> Tails <td> 0.33 <td> 1
</table>

Source: Example in the HTML spec itself

来源:HTML 规范本身中的示例