html - `Display: Inline-Block` 元素没有正确对齐

标签 html css

<分区>

概览

我有两个 div 元素,类为 col,每个元素都有 50% 的宽度。

我想让他们坐在一起;然而,第二个元素位于第一个元素的基线:

Screenshot Example

代码

注意:左栏的最小宽度为 540 像素,因此您可能需要在全屏模式下预览

div.canvas {
  background-image: url(//www.transparenttextures.com/patterns/asfalt-dark.png);
  padding: 100px 0;
  background-color: #F2E394;
  text-align: center;
}

div.col {
  width: 50%;
  display: inline-block;
}

/* Device Mockups */

div#phone {
  width: 540px;
  height: 540px;
  background: url(//i.imgur.com/ieBaiQ1.png);
  background-size: contain;
  background-position: center center;
  position: relative;
  margin: 0 auto;
}

div#phone div.frame {
  position: absolute;
  top: 85px;
  bottom: 85px;
  left: 165px;
  right: 165px;
  overflow-x: hidden;
  overflow-y: auto;
  border-radius: 3px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
  background: white;
}
<div class="canvas">
  <div class="col">
    <div id="phone">
      <div class="frame">
      </div>
    </div>
  </div><div class="col ta-l">
    <h1>Header 1</h1>
  </div>
</div>

问题

如何确保右列与左列垂直对齐,文本“Header 1”的起始位置与左列顶部相同?

最佳答案

只需将 vertical-align: top 添加到 div.col(默认情况下,内联元素的 vertical-align 设置为 基线——你只需要告诉它对齐到顶部即可)。

div.canvas {

  background-image: url(//www.transparenttextures.com/patterns/asfalt-dark.png);

  padding: 100px 0;

  background-color: #F2E394;

  text-align: center;

}

div.col {

  width: 50%;

  display: inline-block;

vertical-align: top;

}

/* Device Mockups */

div#phone {

  width: 540px;

  height: 540px;

  background: url(//i.imgur.com/ieBaiQ1.png);

  background-size: contain;

  background-position: center center;

  position: relative;

  margin: 0 auto;

}

div#phone div.frame {

  position: absolute;

  top: 85px;

  bottom: 85px;

  left: 165px;

  right: 165px;

  overflow-x: hidden;

  overflow-y: auto;

  border-radius: 3px;

  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);

  background: white;

}
<div class="canvas">
  <div class="col">
    <div id="phone">
      <div class="frame">
      </div>
    </div>
  </div><div class="col ta-l">
    <h1>Header 1</h1>
  </div>
</div>

关于html - `Display: Inline-Block` 元素没有正确对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042810/

上一篇:html - 如何不影响受过滤器影响的元素内的元素?

下一篇:html - 如何将 HTML 剪切并粘贴到 Microsoft Word 并获得样式?

相关文章:

html - 最大宽度对表格单元格大小的影响

css - 动画 SVG 线

html - 控制字幕文本

javascript - 用 Javascript 在棋盘上画箭头

html - 如果不是一行的第一个单词,则添加 css 边距

html - 建议 : MoSTLy custom HTML & CSS with a bit of Content Management

html - 奇怪的 Firefox 溢出/ float 行为

javascript - jQuery 删除操作并显示警报

html - 使用 CSS (Wordpress) 删除页脚下方的空白

javascript - css中的按钮对齐