mortenstarck
mortenstarck

Reputation: 2803

HTML Table alignment both ways

I have an table with two columns:

<table border="1" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="250" cellpadding="3" cellspacing="3">
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
    <tr>
        <td>Table Cell</td>
        <td>Table Cell</td>
    </tr>
</table>
<p style="font-family:verdana,arial,sans-serif;font-size:10px;"><a href="http://www.quackit.com/html/html_table_tutorial.cfm" target="_top">HTML Tables</a></p>

I have a problem with the text. How can I align the left text to the left and the right side text to the right? Are there other ways of doing it?

Upvotes: 1

Views: 282

Answers (4)

Sirko
Sirko

Reputation: 74106

There are multiple ways of doing this. One would be to use the :first-child and :last-child pseudo classes:

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

Example Fiddle

Upvotes: 0

Levi Botelho
Levi Botelho

Reputation: 25234

The following CSS will take the second td in each row and set the text-align CSS property to align to the right.

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

You can (and probably should) of course add a class to your table and to this rule so that it applies only to the specific table that you want to align this way.

You can also use this to select the cell in the second column:

td:nth-child(2)

but keep in mind that as it is a CSS3 property it is not as widely supported as my first example.

Upvotes: 5

Ortiga
Ortiga

Reputation: 8834

CSS:

table tr td:first-child {
    text-align:left;
}

table tr td:nth-child(1) { // or :last-child
    text-align:right;
}

Note that these are CSS3 selectors, and thus won't work as-is on older browsers.

Upvotes: 1

Dharman
Dharman

Reputation: 33403

Use classes:

td.leftSide {
    text-align:left;
}

td.rightSide {
    text-align:right;
}

Upvotes: 0

Related Questions