水平居中
1.通过margin:0 auto
给需要居中的容器直接设置margin:0 auto;
css代码:
.father{
width: 300px;
height: 300px;
background-color: bisque;
}
.son{
width: 100px;
height: 100px;
background-color: cadetblue;
margin: 0 auto;
}
2.子绝父相
给需要居中的容器设置绝对定位,对其父容器设置相对定位,然后对居中容器添加left:50%,并使用margin-left:-居中容器宽度的一半;
.father{
width: 300px;
height: 300px;
background-color: bisque;
position: relative;
}
.son{
width: 100px;
height: 100px;
background-color: cadetblue;
position: absolute;
left: 50%;
margin-left: -50px;
}
3.flex布局
在父容器中开启flex布局,再添加justify-content:center
.father{
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
justify-content: center;
}
.son{
width: 100px;
height: 100px;
background-color: cadetblue;
}
2.垂直居中
1.子绝父相
方法跟水平居中类似,只是将水平方向改为垂直方向,所以需要将left改为top。
.father{
width: 300px;
height: 300px;
background-color: bisque;
position: relative;
}
.son{
width: 100px;
height: 100px;
background-color: cadetblue;
position: absolute;
top: 50%;
margin-top: -50px;
}
也可以结合margin使用,把要垂直居中的元素相对于父元素绝对定位,top和bottom设置为相等的值,再设置margin:auto 0;
.father{
width: 300px;
height: 300px;
background-color: bisque;
position: relative;
}
.son{
width: 100px;
height: 100px;
background-color: cadetblue;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
}
2.flex布局
在父容器中开启flex布局,再添加align-items: center;
.father{
width: 300px;
height: 300px;
background-color: bisque;
display: flex;
align-items: center;
}
.son{
width: 100px;
height: 100px;
background-color: cadetblue;
}