简体   繁体   English

如何使用CSS将表格列中的右对齐数字居中?

[英]How to center right-aligned numbers in table column using CSS?

The picture below illustrates what I'm trying to accomplish: 下图说明了我正在努力实现的目标:

在此输入图像描述

UPD. UPD。 As you see, I need the longest number to be centered in its cell, and all other numbers to be right aligned to the longest number's right border. 如你所见,我需要在其单元格中居中最长的数字,并且所有其他数字要与最长数字的右边界对齐。

UPD 2. The numbers are dynamic (unknown initially). UPD 2.数字是动态的(最初未知)。

There doesn't seem to be any direct CSS method. 似乎没有任何直接的CSS方法。 But you could consider the approach suggested by @CMKanode in a comment. 但您可以在评论中考虑@CMKanode建议的方法。 You would need to preprocess the numbers in the column and compute the largest of them (this requires locale-sensitive parsing since you are using a thousands separator), and then you would left-pad the numbers to the same number of characters, using U+2007 FIGURE SPACE as a space that has the same width as digits. 您需要对列中的数字进行预处理并计算其中最大的数字(这需要区分大小写的解析,因为您使用的是千位分隔符),然后您可以使用U将数字左键填充到相同的字符数+2007将SPACE表示为与数字宽度相同的空格。 And, of course, the column would be declared as centered. 当然,该列将被声明为居中。

So in the example, “5” would be padded to         5 (assuming you use a normal space as thousands separator; U+2009 THIN SPACE might be better, but it has font issues. 因此,在示例中,“5”将填充到        5 (假设您使用普通空间为数千分隔符; U + 2009 THIN SPACE可能更好,但它有字体问题。

The approach would mean that you need to use a font where digits have the same width (most fonts in computers do) and that contains U+2007. 该方法意味着您需要使用数字具有相同宽度的字体(计算机中的大多数字体)并且包含U + 2007。

If the thousands separator were a comma or a period, for example, you would need to use U+2008 PUNCTUATION SPACE in its stead. 例如,如果千位分隔符是逗号或句点,则需要使用U + 2008 PUNCTUATION SPACE。

In the end, I think this would be excessively complicated. 最后,我认为这会过于复杂。 It is probably better to make the column right-aligned but with a suitable left and right padding, selected as a good guess based on the width of the column header and the expected widths of the numbers. 最好使列右对齐,但使用合适的左右填充,根据列标题的宽度和数字的预期宽度选择为一个很好的猜测。

Below is not an ideal solution, since the size of the numbers are initially unknown, but it's a little closer without too much additional tags. 下面不是一个理想的解决方案,因为数字的大小最初是未知的,但是如果没有太多额外的标签,它会更接近。

CSS: CSS:

.numSpan {
    display: inline-block;
    width: 100px;
    text-align: right;
}
td { text-align: center; }

HTML: HTML:

<td>
    <span class="numSpan">5</span>
</td>

Seems to me that you need to have a second table inside your main table to determine the width of the numbered content to be centered but right aligned. 在我看来,您需要在主表中设置第二个表来确定要居中但右对齐的编号内容的宽度。 Checkout out this fiddle: Fiddle Example 看看这个小提琴: 小提琴示例

Example Code: 示例代码:

HTML: HTML:

<table class="container">
    <tr><td class="title">Some Title for Numbers in a Table</td></tr>
    <tr><td>
        <table>
            <tr><td>5 000 000</td></tr>
            <tr><td>5 000</td></tr>
            <tr><td>5</td></tr>
            <tr><td>5 000 000</td></tr>
        </table>
   </td></tr>
</table>​

CSS: CSS:

.container {
    width: 400px;
    border: 1px solid #999;    
}

.title {
    font-weight: bold;
    text-align: center;    
}

.container table {
    margin: 0px auto;   
}

.container table td {
    text-align: right;
}​

Add a div to td: 添加div到td:

<td>
    <div align="center">
        <p style="text-align:right">Text Aligned Right</p>
    </div>
</td>

Then add padding / margins to fine tune the placement of the div. 然后添加填充/边距以微调div的位置。

You can approximate this with CSS. 你可以用CSS来估算它。 Create a class: 创建一个类:

td.rt-ctr {
  text-align:right;
  padding-right:33%;    
}

Then call the class in your chart: 然后调用图表中的类:

<table>
  <tbody>
   <tr>
    <td>Item 1</td>
    <td class="rt-ctr">100.25</td>
   </tr>
   <tr>
    <td>Item 2</td>
    <td class="rt-ctr">99.75</td>
   </tr>
  </tbody>
</table>

Depending upon the width of the column, chart and longest data entry, you may need to adjust the percentage in the CSS. 根据列的宽度,图表和最长的数据输入,您可能需要调整CSS中的百分比。 This approach isn't perfect, but it is responsive and is a pure CSS method. 这种方法并不完美,但它具有响应性,是一种纯CSS方法。

Ok I encountered this problem yesterday , went through all the solutions and came up with my own solution that does not modify the DOM in a significant manner but uses JS but I will list the drawbacks of some of the solutions above 好的,我昨天遇到了这个问题,经历了所有的解决方案,并提出了我自己的解决方案,不会以显着的方式修改DOM但使用JS但我会列出上面一些解决方案的缺点

  1. Padding extra characters works if your font is monospace 如果您的字体是等宽字体,则填充额外字符有效
  2. Creating a fixed padding or fixed width may affect responsive behavior 创建固定填充或固定宽度可能会影响响应行为
  3. Adding a second table inside column is serious DOM manipulation, if you have a 1000 rows and 30 columns, you will start seeing the effects of performance with such a heavy tree 在列中添加第二个表是严格的DOM操作,如果你有1000行和30列,你将开始看到这么重的树的性能影响

HTML (Using Bootstrap 4.1.1) HTML (使用Bootstrap 4.1.1)

<table class="table" id="datatable">
  <thead>
    <tr>
      <th>#</th>
      <th>Symbol</th>
      <th>Price</th>
      <th>Volume</th>
      <th>Market Cap</th>
      <th>Circulating Supply</th>
      <th>Total Supply</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

CSS CSS

.numeric{
  text-align: right;
}


#datatable th, #datatable td{
  text-align: center;
}

.centerspan{
  display: inline-block;
  text-align: right;
  background: yellow;
}

.root-rank, .root-price, .root-market_cap, .root-max_supply{
  background: #efefef;
}

JavaScript JavaScript的

var overview_data = [
    { "rank": 1, "symbol": "BTC", "price": 8004.8, "volume_24h": 5864600000000.0, "market_cap": 137422500058.0, "circulating_supply": 17167512.0, "max_supply": 21000000.0},
    { "rank": 2, "symbol": "ETH", "price": 471.305, "volume_24h": 1930260000.0, "market_cap": 47547607782.0, "circulating_supply": 100885006.0, "max_supply": null},
    { "rank": 3, "symbol": "XRP", "price": 0.454852, "volume_24h": 234947000.0, "market_cap": 17882817260.0, "circulating_supply": 39315683476.0, "max_supply": 100000000000.0},
    { "rank": 4, "symbol": "Bitcoin Cash", "price": 845.04, "volume_24h": 730498000.0, "market_cap": 14580563109.0, "circulating_supply": 17254288.0, "max_supply": 21000000.0},
    { "rank": 5, "symbol": "EOS", "price": 8.14097, "volume_24h": 691908000.0, "market_cap": 7295526131.0, "circulating_supply": 896149492.0, "max_supply": 1000000000.0} 
]


var table = document.getElementById("datatable")
var thead = table.tHead
var tbody = table.tBodies[0]
var colClasses = []


for(var i = 0, len= overview_data.length; i < len; i++){
  var tr = document.createElement("tr")
  for(var j in overview_data[i]){
    var td = document.createElement("td")
    td.classList.add("root-" + j)
    var span = document.createElement("span")
    span.classList.add("centerspan")
    span.classList.add('col-' + j)

    //Add this column classes to keep track of one class per column
    if (!colClasses.includes("col-" + j)){
       colClasses.push('col-' + j)
    }
    var text = document.createTextNode(overview_data[i][j] || -1)
    if(!isNaN(overview_data[i][j])){
      td.classList.add("numeric")
    }
    span.appendChild(text)

    td.appendChild(span)
    tr.appendChild(td)
  }
  tbody.appendChild(tr)
}

//This is the main part
for(var i = 0; i < colClasses.length; i++){
  var items = document.querySelectorAll("." + colClasses[i])
  var max = 0

  //Loop through all the items in the col class
  for(var j = 0; j < items.length; j++){
    //Calculate max width of span containing text inside column
    if(items[j].offsetWidth > max){
       max = items[j].offsetWidth
    }
  }

  //Set width of each span to the max width
  for(var j = 0; j < items.length; j++){
    console.log(max)
    items[j].style.width = max + "px"
  }
}

Snapshot 快照 在此输入图像描述

If I understood correctly, you want something like: 如果我理解正确,你需要这样的东西:

 .right-td { align:right; }

going with 跟着去

<td class="right-td">5000000</td>

I believe the actual td in that table (if it is indeed a table) will have a fixed width, and lots of padding to give the illusion that it's centre-right-aligned. 我相信该table的实际td (如果它确实是一个表)将具有固定的宽度,并且有大量的填充以给出它中心右对齐的错觉。

You could try a crude style such as this: 你可以试试这样的原始风格:

/* For demonstration purposes, a fixed width `th`. */
th.headrowrnum {
    width: 200px;
}

td.rightalignnum {
    width: 100px;
    padding: 0 50px;
    text-align: right;
}

HTML: HTML:

<table>
    <tr>
        <th>Col 1</th>
        <th class="headrowrnum">Col 2</th>
    </tr>
    <tr>
        <td>X</td>
        <td class="rightalignnum">5</td>
    </tr>>
    <tr>
        <td>Y</td>
        <td class="rightalignnum">500</td>
    </tr>
</table>

To achieve that alignment, you should do something like this: 要实现这种对齐,您应该执行以下操作:

HTML: HTML:

<td class="my_td">
    <div class="content">
        12345
    </div>
</td>

CSS: CSS:

.my_td 
{
    width: 200px;
    align: center;
}

.content
{
    width: 100px;
    margin-left: auto;
    margin-right: auto;
    text-align: right;
}

You just need to adapt the widths to meet your requirements, for instance, max digits in the number. 您只需调整宽度以满足您的要求,例如,数字中的最大数字。

Another possible solution is to use media queries. 另一种可能的解决方案是使用媒体查询。 In our case, we have roughly the same number of columns in every table. 在我们的例子中,每个表中的列数大致相同。 So, just change the right padding based on screen size to give the desired right/center alignment: 因此,只需根据屏幕大小更改正确的填充,即可获得所需的右/中心对齐:

@media (min-width: 769px)
{
   td
   {
      &.financial
      {
         padding-right: 5px;
      }
   }
}

@media (min-width: 1100px)
{
   td
   {
      &.financial
      {
         padding-right: 20px;
      }
   }
}

@media (min-width: 1400px)
{
   td
   {
      &.financial
      {
         padding-right: 30px;
      }
   }
}

在CSS中,执行此操作以居中对齐td

td {text-align:center;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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