html - 自动列宽为 `overflow-wrap: break-word`

标签 html css

我有一个包含 3 列的 HTML 表 - ID、时间戳和数据。 ID和时间戳很窄,数据可能很大,有时没有换行,所以我设置了水平滚动条overflow-wrap: break-word .为了让它工作,我需要设置我的 table-layoutfixed .
虽然它有效,但我不喜欢所有列现在都具有相等的宽度。我可以将前两列大小设置为某个固定宽度,但我希望它们适合内容。如何强制前 2 列调整其宽度,第三列占用剩余空间?
这是我的代码示例:

<table style="width: 100%; table-layout: fixed; overflow-wrap: break-word">
  <tr>
    <th>ID</th>
    <th>Time</th>
    <th>Data</th>
  </tr>
  <tr>
    <td>0</td>
    <td>10:11</td>
    <td>some_long_value_that_may_or_may_not_contain_a_space</td>
  </tr>
  <tr>
    <td>1</td>
    <td>10:12</td>
    <td>some_long_value_that_may_or_may_not_contain_a_space</td>
  </tr>
  <tr>
    <td>2</td>
    <td>10:13</td>
    <td>some_long_value_that_may_or_may_not_contain_a_space_and_it_may_be_so_long_that_it_wont_fit_into_the_column_and_needs_to_be_wrapped</td>
  </tr>
</table>

基本上我需要的是以某种方式强制前 2 列忽略 table-layout: fixed或给力overflow-wrap: break-word没有它的工作。

最佳答案

我认为您应该使用 display flex 或在 CSS 中添加一个小的调整,如下所示。

.table-wrap tr > td:nth-child(1),
.table-wrap tr > td:nth-child(2) {
  white-space: nowrap;
}

.table-wrap tr > td:nth-child(3) {
  word-break: break-word;
}

th,td {
  padding: 0px 16px
}
<table class="table-wrap" style="width: 100%;">
  <tr>
    <th>ID</th>
    <th>Time</th>
    <th>Data</th>
  </tr>
  <tr>
    <td>0</td>
    <td>10:11</td>
    <td>some_long_value_that_may_or_may_not_contain_a_space</td>
  </tr>
  <tr>
    <td>1</td>
    <td>10:12</td>
    <td>some_long_value_that_may_or_may_not_contain_a_space</td>
  </tr>
  <tr>
    <td>2</td>
    <td>10:13</td>
    <td>some_long_value_that_may_or_may_not_contain_a_space_and_it_may_be_so_long_that_it_wont_fit_into_the_column_and_needs_to_be_wrapped</td>
  </tr>
</table>

关于html - 自动列宽为 `overflow-wrap: break-word`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66980395/

相关文章:

html - 使用 CSS 的内圆底半径

php - 空白页 Laravel : 50k+ table entries

html - css:更简单的写法:div.markup h1,div.markup h2,div.markup h3{color:#f00;}?

css - jQuery Mobile Radio 字段集具有不同的样式

javascript - 从 javascript 更改 CSS 样式?

html - 删除 CSS 中元素之间的空白

javascript - 如何使用react js中的输入复选框返回true或false?

css - Div 在窗口调整大小时重叠

css - 第 n 个 child 对类没有反应

html - CSS 上一个元素