Peter
Peter

Reputation: 1759

Strange behavior when putting 2 divs next to each other

I want to put 2 divs next to each other centered, like described here. The problem is that it seems that my right div is always a bit under the left one when I put a <span> and a heading into the right div. Why does this happen and how can I avoid this?

#right {
  display: inline-block;
  width: 100px;
  height: 160px;
  padding: 15px;
  background: rgba(0, 0, 0, .4);
  border-radius: 1px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .4) inset, 0 1px 0 rgba(255, 255, 255, .2);
}
#wrapper {
  text-align: center;
  padding: 40px;
  height: 160px;
  max-height: 160px;
}
#left {
  display: inline-block;
  width: 100px;
  height: 160px;
  padding: 15px;
  background: rgba(0, 0, 0, .4);
  border-radius: 1px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .4) inset, 0 1px 0 rgba(255, 255, 255, .2);
}
<div align="center" id="wrapper">
  <div id="left"></div>
  <div id="right">
    <span style="text-decoration: underline;">Heading</span>
    <div id="some-content"></div>
  </div>
</div>

Upvotes: 0

Views: 60

Answers (2)

Johannes
Johannes

Reputation: 67768

inline-blockelements are aligned according to the baseline of the included text. If there is no text, the bottom border will act as the baseline. In you example, the bottom border of the left DIV is aligned with the baseline of the text in the right div. If you erase the text (independently from the span tag), they are aligned. If there is text in both boxes, they will be aligned by their lowest text lines (see here: http://codepen.io/anon/pen/YqpJRg)

To align both boxes, use display: block and float: lefton the two DIVs, and for the wrapper position: relative; and margin:auto PLUS a fixed width (the sum of both DIV widths) to center it.

Here's a codepen of the result: http://codepen.io/anon/pen/mPOzaZ

Upvotes: 0

Nutshell
Nutshell

Reputation: 8537

Use vertical-align:top; on the #right and #left divs to get the wanted result

#right {
  display: inline-block;
  width: 100px;
  height: 160px;
  vertical-align:top;
  padding: 15px;
  background: rgba(0, 0, 0, .4);
  border-radius: 1px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .4) inset, 0 1px 0 rgba(255, 255, 255, .2);
}
#wrapper {
  text-align: center;
  padding: 40px;
  height: 160px;
  max-height: 160px;
}
#left {
  display: inline-block;
  vertical-align:top;
  width: 100px;
  height: 160px;
  padding: 15px;
  background: rgba(0, 0, 0, .4);
  border-radius: 1px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .4) inset, 0 1px 0 rgba(255, 255, 255, .2);
}
<div align="center" id="wrapper">
  <div id="left"></div>
  <div id="right">
    <span style="text-decoration: underline;">Heading</span>
    <div id="some-content"></div>
  </div>
</div>

Upvotes: 1

Related Questions