1. 使用flex布局
给父元素设置display: flex;align-items: center; justify-content: center;
子元素设置为margin: auto。
.parent {
width: 500px;
height: 500px;
background-color: #00f;
display: flex;
justify-content: center;
align-items: center;
}
.son {
width: 200px;
height: 200px;
background-color: skyblue;
margin: auto 0;
}
2. 使用定位及transform
定位使用注意子绝父相;
.par {
width: 500px;
height: 500px;
background-color: #00f;
position: relative;
} /* 父元素 */
.son {
width: 200px;
height: 200px;
background-color: skyblue;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
3. 使用grid布局
将父元素设置为display: grid;,子元素设置为justify-self: center; align-self: center;
.par {
width: 500px;
height: 500px;
background-color: #00f;
display: grid;
}
.son {
width: 200px;
height: 200px;
background-color: skyblue;
justify-self: center;
align-self: center;
}
如有错误还请批评指针,欢迎补充