html - 我可以通过 CSS 设置表格单元格元素的宽度吗?

标签 html css html-table dimensions

我需要为内容超过某个阈值的表格单元格添加省略号。

假设我有这个:

<tr>
  <td><a href="#">Fooooooooooooooooooooo</a></td>
  <td><a href="#">b</a></td>
  <td><a href="#">c</a></td>
  <td><a href="#">d</a></td>
</tr>

目前我正在 CSS 中进行设置:

table tr td a,
table tr th a {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

table tr th:first-child:nth-last-child(4),
table tr th:first-child:nth-last-child(4) ~ th,
table tr td:first-child:nth-last-child(4),
table tr td:first-child:nth-last-child(4) ~ td {
  max-width: 25%;
}

但它不起作用 = 表格单元格不限于可用宽度的 25%。

问题:
是否可以在 CSS 中设置表格单元格宽度?或者我可以只定位表格单元格的内容吗?

最佳答案

通常情况下,表格的单元格采用定义的 css 宽度,但它会增长以适应其内联/ block 内容,忽略定义的规则。

一个可能的解决方案是从正常流中移除 anchor ,将其设置为 position: absolute; 并使其全宽。这将阻止单元格扩展,并将 anchor 限制为可用单元格宽度的 100%

记得将表格单元格设置为 position: relative 以便它充当容器

还要记住设置表格的宽度,否则 25% 将毫无意义

table tr td a,
table tr th a {
  position: absolute;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

table {
    width: 200px;
}

table tr th:first-child:nth-last-child(4),
table tr th:first-child:nth-last-child(4) ~ th,
table tr td:first-child:nth-last-child(4),
table tr td:first-child:nth-last-child(4) ~ td {
  max-width: 25%;
    position: relative;
}
<table>
<tr>
  <td><a href="#">Fooooooooooooooooooooo</a></td>
  <td><a href="#">b</a></td>
  <td><a href="#">c</a></td>
  <td><a href="#">d</a></td>
</tr>
</table>

关于html - 我可以通过 CSS 设置表格单元格元素的宽度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26803611/

相关文章:

css - Bootstrap v3.3.0 - 侧面导航

html - 无论屏幕尺寸如何,创建适合父级的图像

javascript - 如何使用 javascript 访问 html 表中每一行的第二个单元格?

javascript - polymer 输入 header 元素没有预期的行为

css - 在 Blogger 简单模板中自定义页脚背景图片

css - Rails Assets 管道 : compressed/minified CSS loaded but not styling document

javascript - 动画扩展/收缩表格

html - 表格属性的最小宽度和最大高度

jQuery 正在删除元素

c# - 使用 Web 表单和 C# 的动态所需页面标题