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

半城伤御伤魂 提交于 2019-12-22 08:34:53

问题


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>

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.


回答1:


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>



回答2:


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


来源:https://stackoverflow.com/questions/33311320/how-to-align-a-div-to-the-left-and-another-div-to-the-center

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