Michel
Michel

Reputation: 23615

Align right in a table cell with CSS

I have the old classic code like this,

<td align="right">

which does what it says: it right aligns the content in the cell. So if I put two buttons in this cell, they will appear at the right site of the cell.

I was refactoring this to CSS, but there doesn't seem to be anything as right align. I see text-align, but is it that the same?

Upvotes: 182

Views: 441018

Answers (4)

Joysn
Joysn

Reputation: 1029

What worked for me now is:

CSS:

.right {
  text-align: right;
  margin-right: 1em;
}

.left {
  text-align: left;
  margin-left: 1em;
}

HTML:

<table width="100%">
  <tbody>
    <tr>
      <td class="left">
        <input id="abort" type="submit" name="abort" value="Back">
        <input id="save" type="submit" name="save" value="Save">
      </td>
      <td class="right">
        <input id="delegate" type="submit" name="delegate" value="Delegate">
        <input id="unassign" type="submit" name="unassign" value="Unassign">
        <input id="complete" type="submit" name="complete" value="Complete">
      </td>
    </tr>
  </tbody>
</table>

See the following fiddle:

http://jsfiddle.net/Joysn/3u3SD/

Upvotes: 10

John Mutuma
John Mutuma

Reputation: 3600

How to position block elements in a td cell

The answers provided do a great job to right-align text in a td cell.

This might not be the solution when you're looking to align a block element as commented in the accepted answer. To achieve such with a block element, I have found it useful to make use of margins;

General syntax

selector {
  margin: top right bottom left;
}

Justify right

td > selector {
  /* there is a shorthand, TODO! 🙂 */
  margin: auto 0 auto auto;
}

Justify center

td > selector {
  margin: auto auto auto auto;
}

/* or the short-hand */
margin: auto;

Align center

td > selector {
  margin: auto;
}

JSFiddle example

Alternatively, you could make you td content display inline-block if that's an option, but that may distort the position of its child elements.

Upvotes: 11

Suite 404 not found
Suite 404 not found

Reputation: 177

Don't forget about CSS3's 'nth-child' selector. If you know the index of the column you wish to align text to the right on, you can just specify

table tr td:nth-child(2) {
    text-align: right;
}

In cases with large tables this can save you a lot of extra markup!

here's a fiddle for ya.... https://jsfiddle.net/w16c2nad/

Upvotes: 16

rahul
rahul

Reputation: 187050

Use

text-align: right

The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.

See

text-align

<td class='alnright'>text to be aligned to right</td>

<style>
    .alnright { text-align: right; }
</style>

Upvotes: 231

Related Questions