我如何将文本居中对齐 <img>
最好使用 FlexBox?
body {
margin: 0px;
}
.height-100vh {
height: 100vh;
}
.center-aligned {
display: box;
display: flex;
box-align: center;
align-items: center;
box-pack: center;
justify-content: center;
}
.background-image {
position: relative;
}
.text {
position: absolute;
}
<section class="height-100vh center-aligned">
<img class="background-image" src="http://vignette2.wikia.nocookie.net/uncyclopedia/images/f/f8/Stand-out-in-the-crowd-300x300.jpg" />
<div class="text">SOME TEXT</div>
</section>
原文由 allegutta 发布,翻译遵循 CC BY-SA 4.0 许可协议
要使文本在图像上居中,您不需要 flexbox。只需使用 CSS 定位属性。
修改后的代码笔
上面的代码将文本在图像上垂直和水平居中:
有关居中方法的更详细说明,请参见: