【问题标题】:How to adjust width of the th as per the td width using css [duplicate]如何使用css根据td宽度调整th的宽度[重复]
【发布时间】:2023-03-13 11:34:01
【问题描述】:

我有一个使用display:block 的表,用于thead 和tbody。如果<td> 中的数据增加,<th> 也需要增加宽度,但现在它不会那样工作....因为display:block ...如何解决这个问题?请有任何建议!

这里我试过css:

table thead,table tbody {
    display: block;
}

table tbody {
    overflow-x: hidden;
    overflow-y: scroll;
    min-height: 90px;
    max-height: 300px;
}

td, th {
    width: auto;
}

【问题讨论】:

  • 请您使用小提琴或其他东西来编写代码?
  • 欢迎来到 SO。您能否通过 sn-p 提供您的代码的运行示例,以便我们更好地查看它?您可以通过编辑您的帖子并使用工具栏中的< >-icon 创建一个 sn-p 来做到这一点。
  • 对不起,我不知道兄弟请给我一个链接或解决方案,td和th的宽度都可以调节吗?如果 td 宽度增加, 宽度也需要增加。因为 display:block 不起作用。
  • @SPYder 你没有做任何努力。抱歉,但这种态度不会让其他人想帮助你。
  • @mbuechmann 请稍等我给个链接

标签: html css


【解决方案1】:

如果文本是非环绕文本,则将单元格设置为宽度:1px 并使用空白:nowrap。该列中的文本将确定单元格的宽度。

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<style type="text/css">

td{width:1px;white-space:nowrap;}
table tbody {
    overflow-x: hidden;
    overflow-y: scroll;
    min-height: 90px;
    max-height: 300px;
}
</style>

<table>
  <thead>
    <tr>
      <th>Column A</th>
      <th>Column B</th>
      <th>Column C</th>
      <th>Column D</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data A.1 lorem</td>
      <td>Data B.1 ip</td>
      <td>Data C.1 sum l</td>
      <td>Data D.1</td>
    </tr>
    <tr>
      <td>Data A.2 ipsum</td>
      <td>Data B.2 lorem</td>
      <td>Data C.2 some data Data D.2 a long line of text that is longData D.2 a long line of text that is longData D.2 a long line of text that is longData D.2 a long line of text that is long</td>
      <td>Data D.2 a long line of text that is longData D.2 a long line of text that is longData D.2 a long line of text that is longData D.2 a long line of text that is long</td>
    </tr>
    <tr>
      <td>Data A.3</td>
      <td>Data B.3</td>
      <td>Data C.3</td>
      <td>Data D.3</td>
    </tr>
  </tbody>
</table>
</body>
</html>

【讨论】:

  • 将添加滚动,td 将根据内容进行调整。
  • 这解决了我自己遇到的一个问题,谢谢! (明天投票,今天没有票)
  • 但我需要一个固定的 如何解决这个问题?为此,我使用了 Display:block..?还有其他方法吗?但是您的解决方案是正确的额外需求作为固定标题 ?
  • TH 有什么问题?
  • 显示块默认不需要写。
【解决方案2】:

试试这个:https://codepen.io/anon/pen/WKVGOw

<table>
  <thead>
  <tr>
    <th>Firstnamee</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  </thead>
   <tobody>
  <tr>
    <td>Jon</td>
    <td>Doe</td> 
    <td>50</td>
  </tr>
  <tr>
    <td>Sam</td>
    <td>Watson</td> 
    <td>34</td>
  </tr>
   </tobody>
</table>


table thead,table tbody {
    display: table-header-group;
}

table tbody {
    overflow-x: hidden;
    overflow-y: scroll;
    min-height: 90px;
    max-height: 300px;
}

td, th {
  max-width: auto;
  text-align: left
}

【讨论】:

  • 显示:表头组;我已经用过这个了。不能在 chrome 中作为滚动的固定标题工作......
猜你喜欢
相关资源
最近更新 更多
热门标签