/* 使用 Flexbox 实现垂直居中 */
.container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 100vh; /* 设置容器高度为视口高度 */
}
/* 使用 Grid 实现垂直居中 */
.container {
display: grid;
place-items: center; /* 同时实现水平和垂直居中 */
height: 100vh; /* 设置容器高度为视口高度 */
}
/* 使用绝对定位和 transform 实现垂直居中 */
.container {
position: relative;
height: 100vh; /* 设置容器高度为视口高度 */
}
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 通过 transform 实现精确居中 */
}
display: flex 和 align-items: center 可以轻松实现子元素在父容器中的垂直居中。justify-content: center 则用于水平居中。display: grid 和 place-items: center 可以同时实现水平和垂直居中,代码更加简洁。position: relative 和子元素的 position: absolute,再结合 top: 50% 和 left: 50% 以及 transform: translate(-50%, -50%) 来实现居中效果。这种方法适用于需要兼容较老浏览器的场景。上一篇:css :before
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站