html - 垂直对齐 100% 宽度图像顶部的两列布局

标签 html css css-tables

我有一个这样的场景,我想要一个宽度为 100% 的图像作为背景。接下来我想在图像中间对齐两列布局文本。我使用 display table cell 和 vertical align: middle 但它没有按预期工作。

JS fiddle here

预期结果是两列布局在中间。 注意:图片必须作为背景,宽度100%,高度根据浏览器宽度缩放。

* {
  margin: 0;
  padding: 0;
}
<div style="position: relative;">
  <img src="https://www.math.nmsu.edu/~pmorandi/math112f00/graphics/rectangle.gif" style="width: 100%; line-height: 0;" />
  <div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0;">
    <div style="display: table; vertical-align: middle; padding-top: 100px;">
      <div style="display: table-cell; width: 120px;">
        Left Column
      </div>
      <div style="display: table-cell;">
        <p>
          Right Column Top
        </p>
        <p>
          Right Column Bottom
        </p>
      </div>
    </div>
  </div>
</div>

enter image description here

最佳答案

如果 flexbox 是一个选项,它可以很容易地删除表格并使用它:

  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;

请注意,我已删除内联样式并添加到类中以供说明:

* {
  margin: 0;
  padding: 0;
}
.container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
<div style="position: relative;">
  <img src="https://www.math.nmsu.edu/~pmorandi/math112f00/graphics/rectangle.gif" style="width: 100%; line-height: 0;" />
  <div class="container">
    <div class="wrapper">
      <div style="width: 120px;">
        Left Column
      </div>
      <div>
        <p>
          Right Column Top
        </p>
        <p>
          Right Column Bottom
        </p>
      </div>
    </div>
  </div>
</div>

如果你想坚持使用表格,这里是解决方案:

  1. height: 100% 添加到 table 并将 vertical-align: middle 添加到 table-cell也用于垂直对齐。

  2. 为水平对齐添加margin: 0 auto

下面的演示:

* {
  margin: 0;
  padding: 0;
}
.container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.wrapper {
  display: table;
  vertical-align: middle;
  height: 100%;
  margin: 0 auto;
}
.wrapper > div {
  display: table-cell;
  vertical-align: middle;
}
.wrapper > div:first-child {
  width: 120px;
}
<div style="position: relative;">
  <img src="https://www.math.nmsu.edu/~pmorandi/math112f00/graphics/rectangle.gif" style="width: 100%; line-height: 0;" />
  <div class="container">
    <div class="wrapper">
      <div>
        Left Column
      </div>
      <div>
        <p>
          Right Column Top
        </p>
        <p>
          Right Column Bottom
        </p>
      </div>
    </div>
  </div>
</div>

关于html - 垂直对齐 100% 宽度图像顶部的两列布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40127411/

相关文章:

javascript - 使用 jQuery 或 AJAX 缩放和倾斜图像

css - 将 <ul> 元素放在右侧(流体导航)

css - 表 - 现在换行成两行?

css - 水平对齐表格行

javascript - 使用 'background-size: contain' 在具有背景的 flexbox 中居中内容

html - 一次只允许播放一个音频元素

html - 如何使用带有模块化比例的 SASS 为所有 header 生成尺寸

javascript - Skrollr、Safari、固定位置滞后

css - 摆脱内联 block 和内联元素之间的空间

python - 添加隐藏的输入类型会改变我的CSS