gpt4 book ai didi

html - 在 flexbox 中将文本居中放置在图像上

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:35 25 4
gpt4 key购买 nike

如何在 <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>

最佳答案

要使文本在图像上居中,您不需要 flexbox。只需使用 CSS 定位属性。

.height-100vh {
height: 100vh;
position: relative; /* establish nearest positioned ancestor for
absolute positioning */
}

.text {
position: absolute;
left: 50%; /* horizontal alignment */
top: 50%; /* vertical alignment */
transform: translate(-50%, -50%); /* precise centering; see link below */
}

body {
margin: 0px;
}

.height-100vh {
height: 100vh;
display: flex; /* establish flex container */
flex-direction: column; /* stack flex items vertically */
position: relative; /* establish nearest positioned ancenstor for absolute positioning */
}

.text {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
color: white;
font-weight: bold;
}

.center-aligned {
display: flex;
align-items: center;
justify-content: center;
}
<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/revision/latest?cb=20090904155448" />
<div class="text">SOME TEXT</div>
</section>

Revised Codepen

上面的代码将文本在图像上垂直和水平居中:

enter image description here

关于居中方法更详细的解释见:

关于html - 在 flexbox 中将文本居中放置在图像上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42250512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com