I have the following code.

<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

Thanks.

2 answers

Doug 1095
1
point
<div style="float:right; width:20%; background:rgba(0,0,0,.2);">
  right most, same line as hello world and will not push hello world!
</div>
<div style="text-align:center; padding-right:20%; padding-left:20%; background:yellow;">
  Hello World
</div>

The padding on the second div keep the contents centered while leaving room for the floated div, but there might be spacing issues on the left side of the div that you will have to watch out for. You can use margin instead of padding (on both or either side) if you don't want the background to extend to the edges. (I used a partial transparency on the floated div to demonstrate the difference between using margin and padding.) The order of the divs is important.

Here's another way that uses absolute positioning instead of floats. You will have to take care with setting widths and min-heights as absolute positioning takes an element out of the flow so there is always the danger of the right-hand div covering up something else on the page. In this example you have to use padding and not margin on the outer div. (The order of the divs is not important in this example, but nesting is.)

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

(Actually, you can use margin on the left of the outer div, but this will change the implied "width" of the div (since margin is not counted in width (in standards-compliant browsers)) so you will have to recalculate the width of the positioned div to take this into account.)

Answered over 8 years ago by Doug
0
points

How about this:

<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>
Answered over 8 years ago by Menno Geelen
  • 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. Yan Cheng CHEOK over 8 years ago