【问题标题】:How to set column width based on the widest cell如何根据最宽的单元格设置列宽
【发布时间】:2020-06-21 01:41:01
【问题描述】:

我正在做一个 Angular 8 项目。我有一个显示表格的页面。根据当前代码,每列的宽度设置如下。宽度仅为th 设置,td 不设置

.data-table tr th:nth-child(1) {
  width: 20%;
}
.data-table tr th:nth-child(2) {
  width: 10%;
}
.data-table tr th:nth-child(3) {
  width: 16%;
}
.data-table tr th:nth-child(4) {
  width: 18%;
}
.data-table tr th:nth-child(5) {
  width: 18%;
}
.data-table tr th:nth-child(6) {
  width: 15%;
}
.data-table tr th:nth-child(7) {
  width: 5%;
}

表中的第一列是Title。我希望设置title 的宽度,使其适合每一行中最长的Title。有没有办法在没有 Javascript 的情况下做到这一点?

【问题讨论】:

  • 您可以在此处使用min-width,并为左列定义width: auto
  • 这能回答你的问题吗? Fit cell width to content
  • @NishargShah 设置 min-widthwidth: auto 不起作用。另外据我所知,min-width 不适用于桌子。
  • 什么?谁说width 属性不能放在桌子上?
  • 宽度有效,我在我的代码中设置宽度。但是我尝试设置 min-width 但它不起作用

标签: html css angular


【解决方案1】:

您也可以用更少的代码做到这一点。

.data-table tr th:nth-child(1) {
  min-width: 20%;
}

.data-table tr th:nth-child(2), .data-table tr th:nth-child(3), .data-table tr th:nth-child(4), .data-table tr th:nth-child(5), .data-table tr th:nth-child(6) {
  max-width: 15%;
}

.data-table tr th:nth-child(7) {
  width: 5%;
}

短版

.data-table tr th:first-child {
  min-width: 20%;
}

.data-table tr th:not(:first-child):not(:last-child) {
  max-width: 15%;
}

.data-table tr th:last-child {
  width: 5%;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 2019-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多