我有一个带有可滚动主体的基本表格。为此,我必须设置 thead 和 tbody display:block 并且我还设置了 th 和 td 的宽度。
由于某些原因,第一列 th 与第一列 tds 不对齐。 谁能告诉我是什么原因造成的?
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;
}
这是 Fiddle
最佳答案
DIV
和 TABLE
的宽度属性工作方式不同。
使用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;
}
编辑:
(编辑答案阐明了 HTML 中宽度的工作原理,如果我有任何错误或遗漏的地方请指出!)
在 div 中,width 属性用于定义元素的大小,内容会相应地适应,而不管父级和兄弟级的宽度。
但在表格的情况下,元素的大小是根据内容计算的,width 属性的优先级较低。甚至 sibling 的大小也被考虑在内。因此,我们必须使用额外的属性,如 min-width
和 max-width
来强制我们想要的尺寸!
关于html - 表格第一列的固定宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40213703/