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

做~自己de王妃 提交于 2019-12-05 11:57:30

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.

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.

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>

Solution:

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 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>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!