/* 方法1: 使用 Flexbox */
.container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 300px; /* 设置容器高度 */
}
/* 方法2: 使用 Grid */
.container {
display: grid;
place-items: center; /* 同时水平和垂直居中 */
height: 300px; /* 设置容器高度 */
}
/* 方法3: 使用绝对定位 + transform */
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 调整元素自身位置 */
}
/* 方法4: 使用 table-cell */
.container {
display: table;
height: 300px; /* 设置容器高度 */
width: 100%; /* 设置容器宽度 */
}
.centered {
display: table-cell;
vertical-align: middle; /* 垂直居中 */
text-align: center; /* 水平居中 */
}
/* 方法5: 使用 line-height (仅适用于单行文本) */
.container {
height: 300px; /* 设置容器高度 */
line-height: 300px; /* 行高与容器高度相同 */
text-align: center; /* 水平居中 */
}
display: flex 和 align-items: center 可以轻松实现垂直居中,同时配合 justify-content: center 实现水平居中。display: grid 和 place-items: center 可以一次性实现水平和垂直居中。position: absolute 将元素放置在容器的中心,再用 transform: translate(-50%, -50%) 调整元素自身的位置。display: table,子元素设置为 display: table-cell,并使用 vertical-align: middle 实现垂直居中。line-height 设置为与容器高度相同,从而实现垂直居中。上一篇:css 设置字体
下一篇:css ::before
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站