简体   繁体   English

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

[英]How to align a div to the left and another div to the center?

Both divs are inside another div :两个 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>

The second div is aligned right not center though.第二个 div 右对齐而不是居中。 How do I get it centered without using tranforms?如何在不使用转换的情况下使其居中? I also need it so it is in one line, no stacking.我也需要它,所以它在一条线上,没有堆叠。

Unfortunately there is no simple method using floats, inline-block or even flexbox which will center the 'middle' div whilst it has a sibling that takes up flow space inside the parent.不幸的是,没有使用浮动、内联块甚至 flexbox 的简单方法可以将“中间”div 居中,同时它有一个兄弟姐妹占用父级内部的流空间。

In the snippet below the red line is the center point.在红线下方的片段中是中心点。 As you can see the left div is taking up some space and so the middle div is not centered.如您所见,左侧 div 占用了一些空间,因此中间 div 未居中。

Sidenote: You can't use float and display:inline block at the same time .旁注:您不能同时使用 float 和 display:inline 块。 They are mutually exclusive.它们是相互排斥的。

 #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>

Solution:解决方案:

You would have to remove one of the elements from the document flow using position:absolute and then position that element accordingly.您必须使用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>

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM