/* 水平居中和垂直居中的几种常见方法 */
/* 方法1: 使用 Flexbox */
.container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 100vh; /* 设置容器高度为视口高度 */
}
/* 方法2: 使用 Grid */
.container {
display: grid;
place-items: center; /* 同时水平和垂直居中 */
height: 100vh; /* 设置容器高度为视口高度 */
}
/* 方法3: 使用绝对定位和 transform */
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 调整元素自身位置 */
}
/* 方法4: 使用表格布局 */
.container {
display: table;
height: 100vh; /* 设置容器高度为视口高度 */
width: 100%; /* 设置容器宽度为100% */
}
.centered {
display: table-cell;
text-align: center; /* 水平居中 */
vertical-align: middle; /* 垂直居中 */
}
Flexbox:通过 display: flex
和 justify-content: center
、align-items: center
可以轻松实现水平和垂直居中。这种方法非常灵活,适用于大多数情况。
Grid:使用 display: grid
和 place-items: center
可以同时实现水平和垂直居中。Grid 布局在处理复杂的布局时非常强大。
绝对定位 + transform:通过 position: absolute
和 transform: translate(-50%, -50%)
可以将元素精确地居中。这种方法适用于固定大小的元素。
表格布局:使用 display: table
和 vertical-align: middle
可以实现垂直居中,而 text-align: center
则用于水平居中。这种方法较为传统,但在某些场景下仍然有用。
上一篇:css流光边框
下一篇:css自适应布局
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站