Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to right align text in HTML Table

Tags:

html

css

I have an HTML table with large number of rows, and I need to right align one column.

I know the following ways,

<tr><td>..</td><td>..</td><td align='right'>10.00</td><tr> 

and

<tr><td>..</td><td>..</td><td class='right-align-class'>10.00</td><tr> 

In both the methods, I have to repeat the align or class parameter on every <tr> tag. (If there are 1000 rows, I have to put align='right' or class='right-align-class' 1000 times.)

Is there any efficient way to do this ? Is there any direct way to say, align the third column in all rows to right ?

like image 594
Palani Avatar asked Aug 26 '09 04:08

Palani


People also ask

How do I right align text in a table in HTML?

HTML | <td> align Attribute left: It sets the text left-align. right: It sets the text right-align. center: It sets the text center-align.

How do you align text in a table row in HTML?

To center align text in table cells, use the CSS property text-align. The <table> tag align attribute was used before, but HTML5 deprecated the attribute. Do not use it. So, use CSS to align text in table cells.

Which symbol is used to right align the text in table?

Right-align text Press Ctrl+R.


1 Answers

Updated (after 10+ years!): Yes! It's possible to do this more efficiently now, with widespread practical browser support, using the nth-child selector.

HTML:

<table> <tr> <td>foo 1</td> <td>bar 1</td> <td>baz 1</td> <td>bap 1</td> </tr> <tr> <td>foo 2</td> <td>bar 2</td> <td>baz 2</td> <td>bap 2</td> </tr> </table> 

CSS:

table td { width: 20em; border: 1px solid black; } table td:nth-child(3) { text-align: end; } 

https://jsfiddle.net/mv83qszL/

Previously, it was not possible to do this, because browser support used to be inconsistent and hit-or-miss, especially with regard to newer CSS features. This made it impossible to use more elegant, efficient solutions -- and required lots of repetitive markup and class definitions in order to get consistent results across the audience's browser space.

See the edit history for the previous version of this answer.

like image 184
Matt Howell Avatar answered Sep 16 '22 17:09

Matt Howell