我想有3个div对齐在一个容器div,就像这样:

[[LEFT]       [CENTER]        [RIGHT]]

容器div是100%宽(没有设定宽度),中心div在调整容器大小后应该保持在中心。

所以我设置:

#container{width:100%;}
#left{float:left;width:100px;}
#right{float:right;width:100px;}
#center{margin:0 auto;width:100px;}

但它变成了:

[[LEFT]       [CENTER]              ]
                              [RIGHT]

任何建议吗?


当前回答

你已经正确地做了,你只需要清除你的浮动。 简单的添加

overflow: auto; 

到容器类。

其他回答

使用CSS3 Flexbox可以很容易地做到这一点,这个功能将在未来被几乎所有浏览器使用(当<IE9完全死亡时)。

查看浏览器兼容性表

HTML

<div class="container">
  <div class="left">
    Left
  </div>
  <div class="center">
    Center
  </div>
  <div class="right">
    Right
  </div>
</div>

CSS

.container {
  display: flex;
  flex-flow: row nowrap; /* Align on the same line */
  justify-content: space-between; /* Equal margin between the child elements */
}

Output: .container { display: flex; flex-flow: row nowrap; /* Align on the same line */ justify-content: space-between; /* Equal margin between the child elements */ } /* For Presentation, not needed */ .container > div { background: #5F85DB; padding: 5px; color: #fff; font-weight: bold; font-family: Tahoma; } <div class="container"> <div class="left"> Left </div> <div class="center"> Center </div> <div class="right"> Right </div> </div>

.processList
  text-align: center
  li
  .leftProcess
    float: left
  .centerProcess
    float: none
    display: inline-block
  .rightProcess
    float: right

html
ul.processList.clearfix
  li.leftProcess

li.centerProcess
li.rightProcess

HTML:

<div id="container" class="blog-pager">
   <div id="left">Left</div>
   <div id="right">Right</div>
   <div id="center">Center</div>    
</div>

CSS:

 #container{width:98%; }
 #left{float:left;}
 #center{text-align:center;}
 #right{float:right;}

text-align:中心;给予完美的中心对齐。

JSFiddle演示

我做了另一次尝试来简化它,并在不需要容器的情况下实现它。

HTML

<div class="box1">left side of the page</div>
<div class="box2">right side of the page</div>
<div class="box3">center of the page </div>

CSS

      .box1 {
      background-color: #ff0000;
      width: 200px;
      float: left;
    }
    
    .box2 {
      background-color: #00ff00;
      width: 200px;
      float: right;
    }
    
    .box3 {
      background-color: #0fffff;
      width: 200px;
      margin: 0 auto;
    }

你可以在JSFiddle现场看到它

你已经正确地做了,你只需要清除你的浮动。 简单的添加

overflow: auto; 

到容器类。