CSS居中问题总结
2020-12-03 本文已影响0人
沉默紀哖呮肯伱酔
1、居中元素宽高固定
- 绝对定位+margin
// top和left 为 50%, margin的left和top为自身宽高一半
.center {
position: absolute;
top: 50%;
left: 50%;
margin-left: -height/2;
margin-top: -width/2;
}
- 绝对定位+calc
.center {
position: absolute;
top: calc(50% - height/2);
left: calc(50% - width/2);
}
2、被居中元素宽高不定
- transform变换
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- flex+auto
.parent {
display: flex;
}
.center {
margin: auto;
}
- flex
.parent{
display: flex;
align-items: center;
justify-content: center;
}