如何将一个div对齐到左侧,另一个div对齐到中心? [英] How to align a div to the left and another div to the center?

查看:35
本文介绍了如何将一个div对齐到左侧,另一个div对齐到中心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个div都在另一个div内:

Both divs are inside another 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虽然没有居中对齐。如何在不使用变形的情况下将其居中?我也需要它,所以它在一行中,没有堆叠。

The second div is aligned right not center though. How do I get it centered without using tranforms? I also need it so it is in one line, no stacking.

推荐答案

不幸的是,没有简单的方法可以使用float,inline-block甚至flexbox来居中居中的div

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.

在红线下方的代码段中是中心点。如您所见,左div占用了一些空间,因此中间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.

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

Sidenote: You can't use float and display:inline block at the same time. 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>

解决方案:

您必须使用 position:absolute ,然后相应地定位 that 元素。

You would have to remove one of the elements from the document flow using position:absolute and then position that element accordingly.

#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对齐到左侧,另一个div对齐到中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆