• 4
name Punditsdkoslkdosdkoskdo

How to adjust 3 divs (left/center/right) inside another div?

I want to have 3 divs aligned inside a container div, something like this:

[[LEFT]       [CENTER]        [RIGHT]]

Container div is 100% wide (no set width), and center div should remain in center after resizing the container.

So I set:

#center{margin:0 auto;width:100px;}

But it becomes:

[[LEFT]       [CENTER]              ]

Any tips?

I like my bars tight and dynamic. This is for CSS 3 & HTML 5

  1. First, setting the Width to 100px is limiting. Don't do it.

  2. Second, setting the container's width to 100% will work ok, until were talking about it being a header/footer bar for the whole app, like a navigation or credits/copyright bar. Use right: 0;instead for that scenario.

  3. You are using id's (hash #container#left, etc) instead of classes (.container.left, etc), which is fine, unless you want to repeat your style pattern elsewhere in your code. I'd consider using classes instead.

  4. For HTML, no need to swap order for: left, center, & right. display: inline-block; fixes this, returning your code to something cleaner and logically in order again.

  5. Lastly, you need to clear the floats all up so that it doesn't mess with future <div>. You do this with the clear: both;

To summarize:


<div class="container">
  <div class="left"></div>
  <div class="center"></div>
  <div class="right"></div>
  <div class="clear"></div>


.container {right: 0; text-align: center;}

.container .left, .container .center, .container .right { display: inline-block; }

.container .left { float: left; }
.container .center { margin: 0 auto; }
.container .right { float: right; }
.clear { clear: both; }

Bonus point if using HAML and SASS ;)




.container {
  right: 0;
  text-align: center;

  .left, .center, .right { display: inline-block; }

  .left { float: left; }
  .center { margin: 0 auto; }
  .right { float: right; }
  .clear { clear: both; }
  • 0
Reply Report

If you do not want to change your HTML structure you can also do by adding text-align: center; to the wrapper element and a display: inline-block; to the centered element.

#container {

#left {

#center {
    display: inline-block;
    margin:0 auto;

#right {

Live Demo:

  • 0
Reply Report

With that CSS, put your divs like so (floats first):

<div id="container">
  <div id="left"></div>
  <div id="right"></div>
  <div id="center"></div>

P.S. You could also float right, then left, then center. The important thing is that the floats come before the "main" center section.

P.P.S. You often want last inside #container this snippet: <div style="clear:both;"></div> which will extend #container vertically to contain both side floats instead of taking its height only from #center and possibly allowing the sides to protrude out the bottom.

  • 0
Reply Report