使此 table 列宽度恰到好处。不太宽也不太窄

Make this table column width fit just nice. Not too wide, not too narrow

我正在使用 angularjs ngtable 模块创建此 table。

这里是相关的html代码;

<div ng-controller="TestCtrl" class="container">
    <table ng-table="tableParams" class="table table-bordered">
        <thead>
        <tr>
            <th>name</th>
            <th>remarks</th>
        </tr>
        </thead>

        <tbody>
        <tr ng-repeat="test in $data">
            <td data-title="'name'" >
                {{test.name}}
            </td>
            <td data-title="'remarks'">
                {{test.remarks}}
            </td>
        </tr>
        </tbody>
    </table>
</div>

name字符串恰好很短。有时,它最多为 5 个字符。有时,最多 3 个字符。 name 的列宽通常比需要的宽。如何让这个栏目恰到好处?

你可以用 css 来完成。添加额外的 class 到您的 table 例如table-expand

所以你的 table 将是

<table ng-table="tableParams" class="table table-bordered table-expand">

和这个 class

的 css
.table-expand tbody tr td:nth-child(1n) {
    white-space:nowrap;
}

.table-expand tbody tr td:nth-child(2n) {
    width:100%
}

看到这个demo

我不知道 ng-table,但我做同样的事情,就像这样

<table>
    <colgroup>
        <col span="1" style="width: 10%;">
        <col span="1" style="width: 90%;">
    </colgroup>

这会导致 name 只有宽度

的 10%

另一个解决方案是使用 css 将 table 设置为 fixed,然后在每个 th 和 [=] 上设置 width 16=]

如果要使列宽根据test.name的内容而定,请确定最长名称中的字符数,并根据字符数设置列宽。

JS

$scope.data = [
    {name: 'a', remarks: 'remark a'},
    {name: 'b', remarks: 'remark b'},
    {name: 'c', remarks: 'remark c'},
    {name: 'defghijk', remarks: 'remark c'}
  ];

  var maxLength = $scope.data.sort(function (a, b) { 
    return (b.name.length - a.name.length); 
  })[0];

  $scope.width = maxLength.name.length * 10 + 'px'

HTML

<div ng-app class="container">
    <table ng-controller="TestCtrl" class="table table-bordered" >
        <thead>
            <tr>
                <th width={{width}}>name</th>
                <th>remarks</th>
            </tr>

        </thead>
        <tbody>
            <tr ng-repeat="test in data">
                <td data-title="'name'" >
                    {{test.name}}
                </td>
                <td data-title="'remarks'">
                    {{test.remarks}}
                </td>
            </tr>
        </tbody>
    </table>
</div>

这里是 working demo