Johan Hjalmarsson Johan Hjalmarsson - 5 months ago 15
HTML Question

Child-element in inline-block div changes the parents siblings position

I have a couple of divs with some content (another div inside). I want the parent divs to be positioned in a nice line and I want the child div to be relative to its parent.

I've made a JSFiddle To illustrate. Right now the divs are all nicely placed, but if you remove the '.btn' div in the last one, everything gets messed up.

To see what I mean, change the HTML in the JSFiddle to:

<div id="expand1" class="expand">
<div id="btn1" class="btn">>></div>
</div>
<div id="expand2" class="expand">
<div id="btn2" class="btn">>></div>
</div>
<div id="expand3" class="expand"></div>


What's going on here? How can I get the desired result?

Answer

You should use floats for a better layout:

.expand{
  border:1px solid black;
  width:400px;
  height:400px;
  display:inline-block;
  float: left;
}

.btn{
  cursor:pointer;
  position:relative;
  top:150px;
  left: 150px;
  border: 1px solid black;
  width:40px;
  height:40px;
  vertical-align:middle;
  text-align:center;
  line-height:40px;
}
<div id="expand1" class="expand">
  <div id="btn1" class="btn">>></div>
</div>
<div id="expand2" class="expand">
  <div id="btn2" class="btn">>></div>
</div>
<div id="expand3" class="expand"></div>