Html 表格第一列的固定宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40213703/
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
Fixed width for table first column
提问by agri
I have a basic table with scrollable body. Doing that I had to set thead and tbody display:block and I also set the width for th and td.
我有一个带有可滚动主体的基本表格。这样做我必须设置 thead 和 tbody display:block 并且我还设置了 th 和 td 的宽度。
For some reason the first column th doesn't line up with the first column tds. Can anyone tell me what causes that?
出于某种原因,第一列 th 与第一列 tds 不一致。谁能告诉我是什么原因造成的?
CSS
CSS
thead,
tbody {
display: block;
}
thead {
text-align: left;
}
tbody {
background: yellow;
overflow-y: auto;
height: 6em;
}
thead th,
tbody td {
width: 4em;
padding: 2px;
}
thead tr th:first-child,
tbody tr td:first-child {
width: 8em;
background: salmon;
font-weight: normal;
}
Here is the Fiddle
这是小提琴
回答by demonofthemist
The width property for DIV
& TABLE
works differently.
DIV
&的 width 属性的TABLE
工作方式不同。
Use max-width
& min-width
to achieve the results you want:
使用max-width
&min-width
来达到你想要的结果:
thead tr th:first-child,
tbody tr td:first-child {
width: 8em;
min-width: 8em;
max-width: 8em;
word-break: break-all;
}
Edit:
编辑:
(Editing the answer clarify the working of width in HTML, please point out if I got something wrong or missed anything!)
(编辑答案阐明了 HTML 中宽度的工作原理,请指出我是否做错了什么或遗漏了什么!)
In divs the width property is used to define the size of the element and the content is fitted in accordingly, irrespective of parent and sibling width.
在 div 中,width 属性用于定义元素的大小,并相应地适应内容,而不管父级和兄弟级的宽度。
But in the case of a table, the size of an element is calculated according to content, and the width property gets a lower priority. Even sibling size is taken into consideration. Thus we have to use additional properties, like min-width
and max-width
to force the size we want!
但是在表格的情况下,元素的大小是根据内容计算的,宽度属性的优先级较低。甚至兄弟姐妹的大小也被考虑在内。因此我们必须使用额外的属性,比如min-width
和max-width
强制我们想要的大小!