1、使用flex布局
方法一:使用主轴侧轴居中
<style>
.father{
/* 使父盒子成为弹性容器*/
display: flex;
/* 水平居中 */
justify-content: center;
/* 垂直居中 */
align-items: center;
width: 400px;
height: 400px;
background-color: gray;
}
.son{
width: 200px;
height: 200px;
background-color: pink;
}
</style>
方法二:使用margin居中(最简单)
<style>
.father{
display: flex;
width: 400px;
height: 400px;
background-color: gray;
}
.son{
margin: auto;
width: 200px;
height: 200px;
background-color: pink;
}
</style>
2、使用定位居中(子绝父相)
方法一:使用transform:translate位移居中
<style>
.father{
/* 父元素相对定位 */
position: relative;
width: 400px;
height: 400px;
background-color: gray;
}
.son{
/* 子元素绝对定位 */
position: absolute;
/* 浏览器的一半 */
left: 50%;
top: 50%;
/* 自身的一半 */
transform: translate(-50% ,-50%);
width: 200px;
height: 200px;
background-color: pink;
}
</style>
方法二:
<style>
.father{
position: relative;
width: 400px;
height: 400px;
background-color: gray;
}
.son{
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
margin: auto;
width: 200px;
height: 200px;
background-color: pink;
}
</style>