我想有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%);
}

码笔链接

其他回答

#warpcontainer  {width:800px; height:auto; border: 1px solid #000; float:left; }
#warpcontainer2 {width:260px; height:auto; border: 1px solid #000; float:left; clear:both; margin-top:10px }

CSS网格可以轻松完成工作:

#{容器 显示:网格;/*(1)一个网格容器*/ grid-auto-flow:列;/*(2)列布局*/ justify-content:之间的空间;/*(3)对齐列*/ 背景颜色:浅黄色; } #容器> div { 宽度:100 px; 身高:100 px; 边框:2px红色虚线; } < div id = "容器" > < div > < / div > < div > < / div > < div > < / div > < / div >

使用CSS网格

layout { display: grid; grid-template-columns: repeat(3,1fr); } start-column { justify-self: start; } center-column { justify-self: center; } end-column { justify-self: end; } <layout> <start-column> <button>Start</button> </start-column> <center-column> <p>Center Donec non urna ipsum. Nullam euismod, lacus ac malesuada varius, mauris erat ullamcorper erat, eget dignissim tortor felis et sapien. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi faucibus turpis et augue dapibus bibendum.</p> </center-column> <end-column> <a href="#">End</a> </end-column> </layout>

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

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

如果你不想改变你的HTML结构,你也可以添加text-align: center;到包装器元素和一个display: inline-block;到居中的元素。

#container {
    width:100%;
    text-align:center;
}

#left {
    float:left;
    width:100px;
}

#center {
    display: inline-block;
    margin:0 auto;
    width:100px;
}

#right {
    float:right;
    width:100px;
}

现场演示:http://jsfiddle.net/CH9K8/