/* 方法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 */
.container {
position: relative;
height: 100vh; /* 设置容器高度为视口高度 */
}
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 移动到中心位置 */
}
/* 方法4:使用表格布局 */
.container {
display: table;
height: 100vh; /* 设置容器高度为视口高度 */
width: 100%; /* 设置容器宽度为100% */
}
.item {
display: table-cell;
text-align: center; /* 水平居中 */
vertical-align: middle; /* 垂直居中 */
}
Flexbox:
display: flex 将容器设置为弹性盒子。justify-content: center 和 align-items: center 分别用于水平和垂直居中。height: 100vh 确保容器高度为整个视口高度。Grid:
display: grid 将容器设置为网格布局。place-items: center 是 justify-items 和 align-items 的简写,用于同时水平和垂直居中。height: 100vh 确保容器高度为整个视口高度。绝对定位和 transform:
.container 设置为相对定位。.item 设置为绝对定位,并通过 top: 50% 和 left: 50% 将元素移动到容器的中心位置。transform: translate(-50%, -50%) 将元素本身向左和向上移动自身宽高的一半,从而实现精确居中。表格布局:
.container 设置为表格显示模式。.item 设置为表格单元格,并通过 text-align: center 和 vertical-align: middle 实现水平和垂直居中。上一篇:css样式优先级
下一篇:css 文字倾斜
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站