在表格中右对齐和居中

8

我经常使用包含数字的表格,这些数字必须右对齐,以便百位、十位和个位数的数字对齐。就像这样:

    2,343
1,000,000
       43
   43,394
  232,111

这些表格中的列标题都是居中对齐的。当表格的列宽很大时,这样看起来并不美观:

         Column 1                    Column 2
===========================|===========================
                     2,343 |                        32     
                        43 |                    44,432
                12,243,394 |                        23 
                   232,111 |                     4,432

有没有一种使用javascript、jQuery或CSS的方法,可以根据最宽的数字将数字居中,但保持右对齐?期望的最终结果应该像这样:
         Column 1                    Column 2
===========================|===========================
             2,343         |              32     
                43         |          44,432
        12,243,394         |              23 
           232,111         |           4,432

我知道可以全局设置td的填充(padding),但我正在寻找一种动态解决方案,能够适应不同的表格,甚至是具有不同列宽和数字宽度的表格。

这可行吗?

5个回答

3

如果你想将数字列居中并靠右对齐,可以使用三列布局,其中左右两列设置为50%。

数字放置在中间列中。由于没有为该列设置宽度,因此它获得最小可能的宽度,即最宽数字的宽度。这个宽度从左右两列中平均分配。

HTML:

<table>
  <colgroup><col width="50%"><col><col width="50%"></colgroup>
  <thead style="text-align:center;">
    <tr><td colspan="3"> /* any optional head line */ </td></tr>
  </thead>
  <tbody style="text-align:right;">
    <tr><td></td><td>123,456,789</td><td></td></tr>
    <tr><td></td><td>456,789</td><td></td></tr>
    <tr><td></td><td>789</td><td></td></tr>
  </tbody>
</table>

只要一列中的所有数字具有相同的小数位数,它就可以正常工作。如果需要,您可以使用左侧列来对齐符号,并使用右侧列显示脚注(左对齐),而不会破坏对齐方式。
对于多个数字列,请使用以下规则,其中n是数字列数,x_i是第i个数字列所需宽度的一半,sum(x_i)=100:
<table>
  <colgroup>
    <col width="x_i %"><col><col width="x_i %"> // for each number column
  </colgroup>
  <thead style="text-align:center;">
    <tr><td colspan="3*n"> /* table head line */ </td></tr>
    <tr><td colspan="3"> /* column head line */ </td></tr> // for each number column
  </thead>
  <tbody style="text-align:right;">
    <tr>
      <td></td><td> /* number */ </td><td></td> // for each number column
    </tr>
  </tbody>
</table>

这非常聪明 - 我必须试一试。 - supertrue

1

显而易见的技巧是使用额外的表格单元格。即:

         Column 1                   Column 2
===========================|===========================
      .      2,343 .       |        .     32 .    
      .         43 .       |        . 44,432 .
      . 12,243,394 .       |        .     23 .
      .    232,111 .       |        .  4,432 .

其中.表示具有自动宽度的不可见表边框。


为了正确对齐表头,应该在<th>(表头单元格)上设置colspan="3"属性。 - Rob W
我的目标是使其易于使用并保持语义化,因此我不想手动添加大量自定义单元格。这些表格由TinyMCE中的非程序员进行编辑。 - supertrue
那么这些数字不是来自后端数据源,比如数据库之类的东西吗?你只有纯粹的HTML,并没有生成它吗? - Vapire
很难在没有额外元素和动态宽度的情况下完成。您可以为 td 标签设置左右填充,并使用 JavaScript 在水平滚动条可见时自动减小它。将文本包装在具有 min-width:10em; text-alignment:rightspan 中,但可能也无法与 TinyMCE 兼容。 - Has QUIT--Anony-Mousse
尝试不错,但想法不好。我有7个数据单元需要在1400行中居中右对齐,这将导致3倍数量的空单元格,页面渲染会出现大问题,难道没有解决方法吗? - PirateApp

1
我会提供一个不同的答案,而不是更改标记以满足您的需求:
使用jQuery的width()函数并遍历列标题,检查/存储它们的宽度。然后要么添加预定义类(带填充),要么更改列中每个单元格的TD填充。
大致如下:
jQuery("thead td").each(function(columnIndex)
{
    var width=jQuery(this).width();

    jQuery(":not(thead) > tr").each(function()
    {                               
        jQuery(this).find("td").eq(columnIndex).css("padding-right",width/2);
    });
});

看它如何运作:http://jsfiddle.net/Y5rw4/3/


这并未考虑不同单元格中文本宽度的差异。右侧填充必须根据最宽的文本来为每列进行调整。换句话说,右侧填充需要是 (columnWidth - widestText)/2 - supertrue

0
你可以将 td 文本包装到一个 <span> 中,然后使用 Math.max.apply(null, Array) 查找 max-width 并将一些 CSS 规则应用到 span 中,如下所示。

$("td").wrapInner("<span></span>");
var arr = [];
var columns = $("table").find("tr")[0].cells.length;
var rows = $("table").find("tr").length - 1;
for (i = 0; i < columns; i++) {
  for (j = 1; j <= rows; j++) {
    arr.push($('table tr:eq("' + j + '") td:eq("' + i + '") span').outerWidth());
  }
  //console.log(arr);
  //console.log(Math.max.apply(null, arr));
  $('table tr').find('td:eq("' + i + '") span').css('width', Math.max.apply(null, arr))
  arr = [];
}
body {
  font: 14px Monospace;
}

table {
  border-collapse: collapse;
}

th,
td {
  text-align: center;
  border: 1px solid #cccccc;
  padding: 6px;
}

td span {
  display: inline-block;
  text-align: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <th>Column 1</th>
    <th>Column 2</th>
  </tr>
  <tr>
    <td>2,343</td>
    <td>32</td>
  </tr>
  <tr>
    <td>43</td>
    <td>44,432</td>
  </tr>
  <tr>
    <td>12,243,394</td>
    <td>23</td>
  </tr>
  <tr>
    <td>232,111</td>
    <td>4,432</td>
  </tr>
</table>


0
好的,我看了一些答案,发现很难接受添加完全没有作用的额外列的想法。我建议采用更好的方法,即在每个字符的开头添加不间断空格,并将所有内容居中对齐,而不添加额外的列。 使用下面的函数在字符串的开头填充额外的字符序列。
function padString(pad, str, leftPadded) {
    if (str === undefined) return pad;
    if (leftPadded) {
        return (pad + str).slice(-pad.length);
    } else {
        return (str + pad).substring(0, pad.length);
    }
}

var coin, newRow, newCell, value, newText
var spaces = new Array(4).fill('\u00A0').join('')
for(let i = 0; i < 1400; i++){
// Insert a row in the table at row index 0
    newRow = tbody.insertRow(i);

  // Insert a cell in the row at index 0
    newCell = newRow.insertCell(0);
    newCell.className = 'rank'

    value = padString(spaces,''+ (i + 1) ,true)
  // Append a text node to the cell
    newText = document.createTextNode(value);
    newCell.appendChild(newText);   
}

所有列都是居中对齐的,但在每个项目前面加上额外的不间断空格后,它们都变成了居中右对齐


这种方法的严重限制是字体必须是等宽的,还有其他人知道更好的解决方案吗? - PirateApp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接