1. 水平居中
1.1 被设置元素为行内元素,设置父元素:
.parent {
text-aligen: center;
}
1.2 被设置元素为块状元素
/* 元素定宽时 */
.item {
margin: 0 auto;
}
1.3 fit-content + margin
.parent {
width: fit-content;
margin: auto;
}
1.4 通过flex布局
.parent {
display: flex;
justify-content: center;
}
2.垂直居中
2.1 line-height + height
前提是:父元素高度确定
/* 单行文本的竖直居中的方法是通过设置父元素的 height 和 line-height 高度一致来实现的*/
.parent {
height: 100px;
line-height: 100px;
}
/* 同时对元素要使其垂直居中,可设置其display: inline-block */
.parent {
line-height: 100px;
height: 100px;
}
.item {
line-height: initial; /* 重置 */
vertical-align: middle;
display: inline-block;
}
2.2 vertical-align
vertical-align
用来指定行内元素(inline)或表格单元格(table-cell)元素的垂直对齐方
2.3 .flex布局
.parent {
display: flex;
align-items: center;
}
3.水平垂直居中
3.1 flex实现
.parent {
display: flex;
justify-content:center;
align-items:center;
}
3.2 grid布局实现
.parent {
display: grid;
}
.item {
justify-self: center; /* 水平居中 */
align-self: center; /* 垂直居中 */
}
3.3 绝对定位+tranform
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* translate移动的时候,以元素本身的宽高为准 */
}
以下3种方法都需要被设置元素宽高固定,且设置父元素相对定位
3.4 绝对定位 + calc
前提时,元素的宽高要固定
.parent {
position: relative;
}
.child {
width: 100px;
height: 100px;
position: absolute;
left: calc(50% - 50px); /* 元素本身宽100px */
top: calc(50% - 50px); /* 元素本身高100px */
}
3.5 绝对定位 + 负margin
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px; /* 元素本身宽100px */
margin-top: -50px; /* 元素本身高100px */
}
3. 6 绝对定位 + margin: auto
.parent {
position: relative;
}
.child {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}