前端学习5 水平垂直居中
在前端中我们主要使用以下方法来实现水平垂直居中
1.单行文本
line-height + text-align
.box {
width: 400px;
height: 200px;
line-height: 200px; /* 控制行高(行间距) */
text-align: center; /* 控制文本水平对齐方式 */
}
2.多行文本或盒子
2.1 flex 弹性布局
.container {
display: flex; /* 启用 Flex 布局 */
justify-content: center; /* 主轴(默认横向)居中 */
align-items: center; /* 交叉轴(默认纵向)居中 */
height: 100vh; /* 必须设置容器高度 */
}
所有居中方法都需要明确容器尺寸,如不设置容器高度,我们将无法计算居中位置,如果是全屏居中,推荐使用height:100vh(100vh是一个相对单位,表示视口高度的100%)。
2.2 定位 + transform
父级设置为相对定位(position: relative),子级绝对定位(position: absolute)
.container {
position: relative; /* 定位基准 */
height: 100vh;
}
.content {
position: absolute;
top: 50%; /* 向下移动50% */
left: 50%; /* 向右移动50% */
transform: translate(-50%, -50%); /* 回退自身尺寸50% */
}
2.3 定位 + margin:auto
父级设置为相对定位(position: relative),子级绝对定位(position: absolute)
.container {
position: relative; /* 定位基准 */
width: 500px;
height: 300px;
}
.content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto; /* 关键属性,自动计算剩余空间均分 */
width: 200px; /* 必须指定尺寸,否则元素会填满父容器 */
height: 100px;
}
2.4 grid布局
.container {
display: grid;
place-items: center; /* 双向居中 */
height: 100vh;
}
display: grid 创建网格容器
place-items 是以下属性的简写:
align-items: center(垂直方向)
justify-items: center(水平方向)
2.5 表格布局
.container {
display: table;
width: 100%;
height: 100vh;
}
.inner {
display: table-cell;
text-align: center; /* 水平居中 */
vertical-align: middle; /* 垂直居中 */
}
.content {
display: inline-block; /* 必须设置为行内块 */
}
display: table 模拟表格布局
table-cell 模拟单元格
结合表格单元格的对齐特性
#前端css#