将2个div放在一起时的奇怪行为

时间:2016-03-15 20:45:53

标签: html css

我想将2个div放在彼此旁边,就像描述here一样。问题是,当我将<span>和一个标题放入正确的div时,似乎我的右侧div总是略低于左侧。为什么会发生这种情况,我该如何避免这种情况?

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

2 个答案:

答案 0 :(得分:1)

在#right和#left div上使用vertical-align:top;来获得想要的结果

&#13;
&#13;
#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);
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

inline-block元素根据所包含文本的基线进行对齐。如果没有文本,则底部边框将充当基线。在您的示例中,左侧DIV的下边框与右侧div中文本的基线对齐。如果您删除文本(独立于span标记),则它们会对齐。如果两个框中都有文本,则它们将按其最低文本行对齐(请参阅此处:http://codepen.io/anon/pen/YqpJRg

要对齐这两个框,请在两个DIV上使用display: blockfloat: left,并为包装position: relative;margin:auto加上固定宽度(两个DIV的总和)宽度)以它为中心。

以下是结果的代码:http://codepen.io/anon/pen/mPOzaZ

相关问题