tags:

views:

42

answers:

3

I had posted the question once to http://doctype.com/within-same-line-have-center-element-right-most-element, but didn't get a good answer for that. I posted it here and hopefully will get a good feedback ;)

<div style="float:right">
    right most, same line as hello world and will not push hello world!
</div>

<div style="text-align:center">hello world</div>

Currently, the right most element, will push the "hello world" out from center of the page. How can I avoid this?

I wish

  • Hello world is still at center
  • The right element is still same line as Hello world
  • The right element is at right most
  • Both are top most

Thanks.

I tried some suggestion by others but it won't work.

<div style="text-align:center; width:100%;"> 
  Hello World 
  <div style="float:right">right most, same line as hello world and will not push hello world!</div>
  <div style="clear:both"></div>
</div>

For the above code, I tested with IE 8. They will not be at same line. And I tested with firefox 3.6.8, The "Hello World" will be pushed toward left by the right side element.

+2  A: 

Use position:relative on the containing div and position:absolute; right:0px; top:0px; on the rightmost div:

<div style="text-align:center; width:100%; position:relative;"> 
  Hello World 
  <div style="right:0px; top:0px; position:absolute;">right most, same line as hello world and will not push hello world!</div>
  <div style="clear:both"></div>
</div>

When position:relative is used, any absolutely positioned elements inside are offset to that relatively positioned ancestor. See this blog post for further examples.

Demo - http://jsbin.com/itene

Andy E
Brilliant. It just work!
Yan Cheng CHEOK
A: 

Try this:

<div style="text-align:center; width:100%;">
  <div style="float:left; margin-left:400px;">Hello World </div>
  <div style="float:right">right most, same line as hello world and will not push hello world!</div>
  <div style="clear:both"></div>
</div>

See the DEMO here.

You might want to adjust the value for margin-left in the hello world div.

Sarfraz
A: 

Specify a line height for the centered div and use position: relative for the second:

<div style="text-align:center; line-height: 50px;">hello world</div>
<div style="line-height: 50px; position: relative; top: -50px; float:right; z-index: 1">
    right most, same line as hello world and will not push hello world!
</div>
Anax
Sorry. I realize both stuffs are shifting down. Is it possible to maintain them as top most too?
Yan Cheng CHEOK
Yes, by altering the line-height. Try a value less than 50px.
Anax