Why can I not right-align an element with display: block and width: X?

Dan Tao picture Dan Tao · May 8, 2012 · Viewed 24.5k times · Source

Total n00b question here (at least to the CSS elite):

Why is it that an element with both display: block; and a value for width does not seem to fall in line with the text-align property of its parent? That is, it always seems to insist on keeping to the left.

Here is a jsFiddle illustrating the issue.

Obviously, this must be consistent with the CSS spec (I mean, if Chrome, Firefox and Opera all agree on it, I have very little doubt); I just don't really get it.

Answer

michaelward82 picture michaelward82 · May 8, 2012

The text is aligned right inside a 150px box. That is correct. A block element will not align to text-align in the parent.

To fix this you need to use either display: inline-block or float: right on the .width div.

edit: with float, add clear: right to avoid it being on the same line as the previous div