
Flexbox 和 CSS 定位中图像上的文本居中
将文本置于图像上居中是常见的布局要求。虽然 Flexbox 提供了强大的对齐选项,但您还可以使用 CSS 定位属性来实现此效果。
使用绝对定位
使用绝对定位使文本在图像上居中:
1 2 3 4 5 6 7 8 9 10 | body {
position: relative;
}
...
.text {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
|
登录后复制
- 为 body 设置一个静态位置值,为绝对值建立一个定位的祖先定位。
- 绝对定位文本元素。
- 文本左水平居中:50%;并将其与顶部垂直居中:50%;。
- 使用变换通过平移其宽度和高度的一半来微调居中。
使用 Flexbox
或者,Flexbox 可用于图像和文本定位:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | body {
margin: 0px;
}
...
.height-100vh {
height: 100vh;
display: flex;
flex-direction: column;
position: relative;
}
...
.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;
}
|
登录后复制
- 将图像和文本元素包裹在具有高度属性的Flexbox容器中。
- 设置align-items: center;并调整内容:中心;在容器内垂直和水平对齐项目。
- 将文本元素绝对定位在容器内并根据需要设置其样式。
以上是如何使用 Flexbox 和 CSS 定位使文本在图像上居中?的详细内容。更多信息请关注PHP中文网其他相关文章!