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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:58:06  来源:igfitidea点击:

Fixed width for table first column

htmlcss

提问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& TABLEworks differently.

DIV&的 width 属性的TABLE工作方式不同。

Use max-width& min-widthto 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-widthand max-widthto force the size we want!

但是在表格的情况下,元素的大小是根据内容计算的,宽度属性的优先级较低。甚至兄弟姐妹的大小也被考虑在内。因此我们必须使用额外的属性,比如min-widthmax-width强制我们想要的大小!

回答by hairmot

remove your first style rule: display:block from tbody and thead

删除您的第一个样式规则: display:block from tbody 和 thead

By doing this, you are over-riding the table formatting and layout that display:table provides

通过这样做,您将覆盖 display:table 提供的表格格式和布局

thead,
tbody {
 // display: block;
}

Fixed

固定的