1 通过绝对定位和相对定位
经常看见有人分什么子元素宽度已知和宽度未知,这两个其实就是一种情况。用百分比是通吃的。原理就是top 50% 和 left 50% 的时候是以左上角为基准的,左上角居中了,这时候只要把自己再反过来移动半个宽度和高度就变成真正的居中了
.father {
border:1px solid black;
height:400px;
width:400px;
position: relative;
}
.son{
border:1px solid red;
height:100px;
width:100px;
position:absolute;
top: 50%;
left:50%;
transform: translate(-50%,-50%);
}
不反向移动半个宽度和高度的话,左上角是居中的。
加上transform: translate(-50%,-50%);
就正好居中了
还有什么margin: -50px 0 0 -50px;
这种已知子元素宽度的用法,你累不累啊这么写还要除以二来个计算。能省事就省事。
2 flex弹性盒子的 align-items,justify-content
这个就是flex布局时候,控制子元素的水平位置和垂直位置的两个属性。直接都center就是居中了
.father {
border:1px solid black;
height:400px;
width:400px;
display: flex;
align-items: center;
justify-content: center;
}
.son{
border:1px solid red;
height:100px;
width:100px;
}
3 flex弹性盒子,子元素margin:auto
这个是代码最少的一种方法了
.father {
border:1px solid black;
height:400px;
width:400px;
display: flex;
}
.son{
border:1px solid red;
height:100px;
width:100px;
margin: auto
}