我想有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]

任何建议吗?


当前回答

可能的答案,如果你想保持HTML的顺序而不使用flex。

HTML

<div class="a">
  <div class="c">
    the 
  </div>
  <div class="c e">
    jai ho 
  </div>
  <div class="c d">
    watsup
  </div>
</div>

CSS

.a {
  width: 500px;
  margin: 0 auto;
  border: 1px solid red;
  position: relative;
  display: table;
}

.c {
  display: table-cell;
  width:33%;
}

.d {
  text-align: right;
}

.e {
  position: absolute;
  left: 50%;
  display: inline;
  width: auto;
  transform: translateX(-50%);
}

码笔链接

其他回答

用twitter引导:

<p class="pull-left">Left aligned text.</p>
<p class="pull-right">Right aligned text.</p>
<p class="text-center">Center aligned text.</p>

可能的答案,如果你想保持HTML的顺序而不使用flex。

HTML

<div class="a">
  <div class="c">
    the 
  </div>
  <div class="c e">
    jai ho 
  </div>
  <div class="c d">
    watsup
  </div>
</div>

CSS

.a {
  width: 500px;
  margin: 0 auto;
  border: 1px solid red;
  position: relative;
  display: table;
}

.c {
  display: table-cell;
  width:33%;
}

.d {
  text-align: right;
}

.e {
  position: absolute;
  left: 50%;
  display: inline;
  width: auto;
  transform: translateX(-50%);
}

码笔链接

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

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现场看到它

使用CSS,像这样放置你的div(浮动优先):

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

附注:你也可以向右浮动,然后向左浮动,然后向中心浮动。重要的是,浮动出现在“主”中心部分之前。

P.P.S.你经常想要最后在#容器里的这个片段:<div style="clear:both;></div>,它将垂直扩展#容器以包含两侧浮动,而不是仅从#中心取高度,并可能允许两侧突出底部。

以下是当我用图像作为中心元素时,我必须对接受的答案做出的更改:

确保图像包含在div中(在本例中是#center)。如果不是,你将不得不设置显示为block,它似乎是相对于浮动元素之间的空间居中。 确保设置图像和它的容器的大小: #{中心 保证金:0自动; } #center, #center > img { 宽度:100 px; 高度:汽车; }