如何将 div 左对齐,另一个 div 居中对齐?

How to align a div to the left and another div to the center?

两个div都在另一个div里面:

#container {
  width: 100%;
}

#container > .first {
  display:inline-block;
  float:left;
  width:100px;
}

#container > .second {
  display:inline-block;
  float:right;
  margin: 0 auto;
  width:100px;
}
<div id='container'>
  <div class='first'>Left</div>
  <div class='second'>Right</div>
</div>

第二个 div 是右对齐而不是居中。如何在不使用变换的情况下使其居中?我也需要它,所以它在一行中,没有堆叠。

<div style="width:100%;">
  <div style="display:inline-block;float:left;width:100px;">Div 1</div>
  <div style="display:block;width: 100px;margin: 0 auto;">
      Div 2
  </div>
</div>

不幸的是,没有使用浮动的简单方法,inline-block 甚至 flexbox 将使 'middle' div 居中,同时它有一个占用流的兄弟 space在 parent.

里面

在红线下方的片段中是中心点。如您所见,左边的 div 占用了一些 space,因此中间的 div 没有居中。

旁注:您不能同时使用 float 和 display:inline 块 。它们是互斥的。

#container {
  text-align: center;
  position: relative;
}
#container:after {
  content: '';
  position: absolute;
  left: 50%;
  height: 200%;
  width: 1px;
  background: #f00;
}
#container > .first {
  float: left;
  width: 100px;
  background: #bada55;
}
#container > .second {
  display: inline-block;
  width: 100px;
  background: #c0feee;
}
<div id='container'>
  <div class='first'>Left</div>
  <div class='second'>Center</div>
</div>

解法:

您必须使用 position:absolute 从文档流中删除其中一个元素,然后相应地放置 那个 元素。

#container {
  text-align: center;
  position: relative;
}
#container:after {
  content: '';
  position: absolute;
  left: 50%;
  height: 200%;
  width: 1px;
  background: #f00;
}
#container > .first {
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  background: #bada55;
}
#container > .second {
  display: inline-block;
  width: 100px;
  background: #c0feee;
}
<div id='container'>
  <div class='first'>Left</div>
  <div class='second'>Center</div>
</div>