Html 相同大小的表格单元格以填充包含表格的整个宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1457563/
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-29 00:53:25  来源:igfitidea点击:

Equal sized table cells to fill the entire width of the containing table

htmlcsshtml-table

提问by yogibear

Is there a way using HTML/CSS (with relative sizing) to make a row of cells stretch the entire width of the table within which it is contained?

有没有办法使用 HTML/CSS(具有相对大小)使一行单元格拉伸包含它的表格的整个宽度?

The cells should be equal widths and the outer table size is also dynamic with <table width="100%">.

单元格的宽度应该相等,并且外部表格的大小也是动态的<table width="100%">

Currently if I don't specify a fixed size; the cells just autosize to fit their contents.

目前,如果我没有指定固定大小;单元格只是自动调整大小以适合其内容。

回答by Simon

You don't even have to set a specific width for the cells, table-layout: fixedsuffices to spread the cells evenly.

您甚至不必为单元格设置特定的宽度,table-layout: fixed就足以均匀地分布单元格。

ul {
    width: 100%;
    display: table;
    table-layout: fixed;
    border-collapse: collapse;
}
li {
    display: table-cell;
    text-align: center;
    border: 1px solid hotpink;
    vertical-align: middle;
    word-wrap: break-word;
}
<ul>
  <li>foo<br>foo</li>
  <li>barbarbarbarbar</li>
  <li>baz</li>
</ul>

Note that for table-layoutto work the table styled element must have a width set (100% in my example).

请注意,table-layout要工作,表格样式元素必须设置宽度(在我的示例中为 100%)。

回答by cletus

Just use percentage widths and fixed table layout:

只需使用百分比宽度和固定表格布局

<table>
<tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
</tr>
</table>

with

table { table-layout: fixed; }
td { width: 33%; }

Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.

固定表格布局很重要,否则如果内容不合适,浏览器将根据其认为合适的方式调整宽度,即宽度是建议,而不是没有固定表格布局的规则。

Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.

显然,调整 CSS 以适应您的情况,这通常意味着仅将样式应用于具有给定类或可能具有给定 ID 的表。

回答by Shashank

Using table-layout: fixedas a property for tableand width: calc(100%/3);for td(assuming there are 3 td's). With these two properties set, the table cellswill be equalin size.

使用table-layout: fixed作为用于属性tablewidth: calc(100%/3);td假设有3td)。设置这两个属性后,表格单元格的大小将相等

Refer to the demo.

请参阅演示