简体   繁体   中英

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

I am using angularjs ngtable module to create this table.

Here is the relevant html code;

<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>

The name string happens to be very short. Sometimes, it is at most 5 characters. Sometimes, at most 3 characters. The column width for name is usually wider than necessary. How to make this column fit just nice?

You can make it with css. Add an extra class to your table eg table-expand

so your table will be

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

and the css for this class

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

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

see this demo

I don't know with ng-table, but I do about the same thing, like this

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

This would cause name to only have 10% of the width

Another solution would be the set the table to fixed using css, then set the set the width on each th and td

If you want to make the width of the column dependent on the content of test.name , determine the number of characters in the longest name and set the width of the column based on character count.

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>

Here's a working demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM