我有一个这样的场景,我想要一个宽度为 100% 的图像作为背景。接下来我想在图像中间对齐两列布局文本。我使用 display table cell 和 vertical align: middle 但它没有按预期工作。
预期结果是两列布局在中间。 注意:图片必须作为背景,宽度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>
最佳答案
如果 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>
如果你想坚持使用表格,这里是解决方案:
将
height: 100%
添加到table
并将vertical-align: middle
添加到table-cell
也用于垂直对齐。为水平对齐添加
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/