views:

4525

answers:

7

Is there an elegant way to align 3 elements left, center, and right on the same line?

Right now I'm using 3 <div>'s all with width:33%;float:left; and it's not working too well.

A: 

Float the first two left and float the third one right, while ensuring the widths will fit the line you are placing them on.

Use pixel widths if your design allows for it.

Chris Ballance
+2  A: 

that works for me:

<html>
  <head>
    <style>
      div.fl {
        float: left;
        width: 33%;
      }
      div.fr {
        float: right;
        width: 33%;
      }
    </style>
  </head>
  <body>
    <div class="fl">
      A
    </div>
    <div class="fl">
      B
    </div>
    <div class="fr">
      C
    </div>
  </body>
</html>

do you mean the same?

Johannes Weiß
A: 

Float LeftBlock 'left', CenterBlock 'none' and RightBlock 'right'. But make sure the Center element appears last on your HTML page, otherwise it wont work.

flesh
+1  A: 

You may get strange results if there is any margin in the element you are adding it to. This is where width: 33% may not work because you will need to factor in the amount of margin that element has.

<html>
<head>
<title></title>
<style type="text/css">
div { float: left; width: 33%; margin: 4px; }
</style>
</head>
<body>

<div style="border: 1px solid #ff0000;">1</div>
<div style="border: 1px solid #00ff00;">2</div>
<div style="border: 1px solid #0000ff;">3</div>

</body>
</html>

This will cause it not work as expected because of the margin added to each div. Similarly, if you add too much of a border to each div you will get a similar result border: 5px solid !important;

As soon as you take away the margin from the above code, it should work as expected.

Gary Green
+1  A: 

Try this:

<div style="float: left; width: 100px;">
 left
</div>
<div style="float: right; width: 100px;">
 right
</div>
<div style="width: 100px; margin: 0 auto;">
 center
</div>

You need to take into account that the left and right divs do not push the container box (a div around the code above) height down, even if they have more content than the center div, the only one not floated. A clearfix will take care of this.

idevelop
A: 

Here is yet another varition of the theme:-

<html>
<head>
<style type="text/css">
 div div {border:1px solid black}
 div.Center {width:34%; float:left; text-align:center}
 div.Left {float:left; width:33%; text-align:left}
 div.Right {float:right; width:33%; text-align:right}
</style>
</head>
<body>
<div class="Left"><div>Left</div></div><div class="Center"><div>Center</div></div><div class="Right"><div>Right</div></div>
</body>
</html>

Note that the border is possible by using an inner div for each of the 'panel' divs. Also gives the center the remain 1% of pixels.

AnthonyWJones
+1  A: 

I created a page with all three methods for comparison at http://www.salestime.com/Ref/LeftCenterRight.html.