kennysong
kennysong

Reputation: 524

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

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.

Upvotes: 4

Views: 18185

Answers (2)

Paulie_D
Paulie_D

Reputation: 115374

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>

Upvotes: 3

Yoan
Yoan

Reputation: 2207

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

Upvotes: 1

Related Questions