Printing table cells from right to left

2019-04-06 06:51发布

问题:

I make a table and want the first cell to start from right instead of from left as default. I tried changing the float attribute in CSS but it doesn't seem to help. Here is the code:

<table border="0" width="100%" cellspacing="0" align="center" class="result_table">
    <tr align="right">
    <th bgcolor="#cccccc" align="right">1</th>
    <th bgcolor="#cccccc" size="17">2</th>
    <th bgcolor="#cccccc">3</th>
    <th bgcolor="#cccccc">4</th>
    </tr>; 

</table>
table.result_table {
    float:right;
}

Can anyone suggest a way to change the float of this table?

回答1:

As suggested in comments, you can set directionality to right-to-left (RTL). However, unless your table content is in a right-to-left language, you should additionally set the directionality in table content elements to left-to-right. Otherwise, they inherit RTL directionality, which will cause surprises in many situations, since the directionality also sets the overall text directionality. This will not affect normal text in a Western language, but it will affect e.g. content like “4 (5)”, which would appear as “(5) 4” with RTL directionality.

Thus, you should set

table.result_table {
  direction: rtl; }
table.result_table caption, table.result_table th, table.result_table td {
  direction: ltr; }


回答2:

I'm not sure if this can be achieved with CSS only. If using jQuery is Ok for you, here's a starting idea that might get you to the desired result:

CSS:

.result_table{float:left; width:100%; border-collapse:collapse; padding:0;}
.result_table th{float:right; padding:0;}

JS:

var cols = $('.result_table th').length;
var colWidth = 100 / cols;
$('.result_table th').css({width:colWidth+'%'})

Example - jsFiddle



回答3:

There is a much easier way. You can add direction="rtl" to the table.

<table dir="rtl">
     ...
</table>