tags:

views:

84

answers:

2

I want to right-align an inline element to the right of a div. I have seen float="right" applied on a span to right align it but it seems semantically incorrect to me as floats are supposed to move "boxes" or block elements to the right or left of a container element.

Is my understanding of Float wrong or is there another way of right-aligning inline elements in a container DIV.

+1  A: 

float: right is perfectly okay applied to all elements, block-level or inline it doesn't matter, either semantically or according to the spec (so far as I'm aware).

If you want to right-align something without using float then there's the possibility of margin-right: 90%; (assuming you know that what it's right-aligned from/against fits into the other 10%.

Or direction: rtl; but that never works like I think it should, plus it'd likely complicate things.

position: absolute; right: 0; would do as you need (but it'd be removed from the document's flow, and it would be positioned against the first of its parent elements that has a defined position: relative; (or at least defined position).

You could, possibly, use text-align: right, but that seems like such a simple solution that I'm sure you'll have already tried it.

If you could provide a use-case, some code and an indication of your expected end-result we might be able to help you more.

David Thomas
+1  A: 

Floating an element automatically makes it into a box. (See: http://css.maxdesign.com.au/floatutorial/introduction.htm ) However, there is nothing semantically incorrect about it. Semantics don't dictate what should be displayed as a block and what should be displayed inline--that's one reason we can declare that arbitrarily. (It certainly becomes messy when you start taking words out of their order--but I doubt that's what you're talking about here, as I can't imagine a case when you'd want to do that and have it remain inline.)

Moreover, if you need to align a bit of inline text independent from the flow of normal text (which is what a float does), you really want to display it as a block anyway. If it's really an inline element, all you need is text-align:right--anything you need a float or a position declared on you are already treating as a block element, so there's nothing wrong with declaring it as such.

D_N
but using Float without width is not recommended and in this I want my width to be = content and hence the inline element? So, if my element is a block element with Float, would not having the width specified hurt ?
Rajat
@Rajat Not having the width specified means that by default your float will shrink to the size of the longest word. You can use white-space:nowrap to override that behavior--then it will be as wide as your content is. (So be sure to put in a BR if you need it to wrap.)
D_N