align right in a table cell with CSS

Viewed 356254

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 2 buttons in this cell, they will appear at the right site of the cell.

But then I was refactoring this to CSS, but there is no such thing as right align? I see text-align, is that the same?

4 Answers

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>

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;
}

JS Fiddle 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.

Related