English 中文(简体)
表格中的权利与中心
原标题:Right-align and center in table

我经常使用含有必须正确调整的数字的表格,以便数字/数字/数字/数字/数字/千差万分。 与此类似:

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

Column headers in these tables are centered. When the table columns are wide, it doesn t look great:

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

是否有办法利用javascript、j Query或CSS来集中数字,但保留正确的理由? 期望的最终结果是:

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

I know I could set td padding globally, but I am looking for a dynamic solution that will adapt to different tables, even with different column width and number width.

能否做到这一点?

问题回答

For a number column you want to align "centered right", use three columns, where the left and right column are set to 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>

It works fine as long as all numbers in a column have the same number of decimal places. If required, you can use the left column to align signs and the right column to display footnotes (left-aligned) without disturbing the alignment.

For more than one number column use following rule, where n is the number of number columns and x_i is half of the desired width of the i-th number column and 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>

明显的骗局是使用额外的桌子。 页: 1

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

<代码>>>表示表面上表边界为自动宽度。

I ll offer a different answer than changing the markup to meet your needs:

使用 j(毛.)功能,通过一栏头 head,检查/储存 w。 然后,在一栏中增加一个预先界定的类别(有dding),或改变每个单元的TDdding。

Something along the lines of this:

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/

All right, I went through some of the answers and find it hard to accept the idea of adding extra columns that serve absolutely no purpose. I will suggest a better method that involves adding non breaking spaces at the start of each character and center aligning everything without adding extra columns Use the function below to pad Strings with an extra character sequence at the start

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);   
}

All columns are center aligned but with the extra non breaking space in front of each item, they all become center right aligned

You can wrap the td text into a <span> and then find the max-width using Math.max.apply(null, Array) and apply some css rules into the span like below

$("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>




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签