Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 637
Dan Tao Avatar asked May 07 '12 23:05

Dan Tao


2 Answers

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

like image 104
michaelward82 Avatar answered Oct 17 '22 06:10

michaelward82


<span> is an element with display: inline. Elements with display: inline following the text alignment. Elements with display: block does not follow the alignment of text are aligned OWNED by the float.

When you just change the width of the element remains inline, following the alignment of text, but when you change your display to block and change its width, its content assumes the alignment of text, but the element does not. I tried to illustrate this with some color in your code ;)

http://jsfiddle.net/Z6Twf/3/

like image 37
Oswaldo Acauan Avatar answered Oct 17 '22 06:10

Oswaldo Acauan