Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning text in a table with CSS

I have a really simple table with two rows and two columns. I want the text in the first column to be right-aligned and the second column to be left-aligned. I'm sure this is really easy but I just can't figure it out.

Here's the HTML:

<table>
 <tr><td>Previous:</td><td>Link 1</td></tr>
 <tr><td>Next:</td><td>Link 2</td></tr>     
</table>

How would I do this?

like image 974
Garry Pettet Avatar asked Mar 22 '12 14:03

Garry Pettet


4 Answers

I would use classes in this instance. You could get fancy but this is the best way for supporting.

CSS

.alignright { text-align: right; }
.alignleft { text-align: left; }

HTML

<td class="alignright"> </td>
<td class="alignleft"> </td>

You could go further by adding padding, margins and further classes. Depending on your TABLE css you might need to add some padding so that the cells aren't all padding: 0 and not showing any alignment.

like image 71
SMacFadyen Avatar answered Nov 10 '22 00:11

SMacFadyen


You can either use :first-child to target the cells in the first column:

td {
    text align: left;
}

td:first-child {
    text-align: right;
}

But :first-child: doesn’t work in IE 6, so you might want to add a class to the cells in the first column, and use that instead:

<table>
 <tr><td class="first">Previous:</td><td>Link 1</td></tr>
 <tr><td class="first">Next:</td><td>Link 2</td></tr>     
</table>

td {
    text align: left;
}

td.first {
    text-align: right;
}

As written, this will apply to all <td> elements, so you might also want to add a class to your table and limit the styles to <td>s in that table:

<table class="simple">
 <tr><td class="first">Previous:</td><td>Link 1</td></tr>
 <tr><td class="first">Next:</td><td>Link 2</td></tr>     
</table>

table.simple td {
    text align: left;
}

table.simple td.first {
    text-align: right;
}
like image 39
Paul D. Waite Avatar answered Nov 10 '22 00:11

Paul D. Waite


As an alternative and given your scenario and if you are able to - why don't you replace the <td>'s in your second column with <th>'s and then the CSS will be really simple:

td { text-align:right; }
th { text-align:left; }
like image 36
Barry Kaye Avatar answered Nov 10 '22 01:11

Barry Kaye


set different classes on each td element

<style>
    td.raligned {text-align: right;} 
    td.leftaligned {text-align: left;} 
</style>

<table>
    <tr>
        <td class="raligned">blah</td>
        <td class="leftaligned">blah</td>
    </tr>
</table>
like image 30
krystan honour Avatar answered Nov 09 '22 23:11

krystan honour