css水平垂直居中的方式
1、用绝对定位实现
Step1:通过**top:50%和left:50%**将元素的左上角定位到页面的中心
Step2:通过**transform: translate(-50%, -50%)**将元素的中心调整到页面的中心
代码实现:
.parent {
width: 200px;
height: 300px;
position: relative;
background-color: bisque;
}
.child {
position: absolute;
left: 50%;
top: 50%;
width: 60px;
height: 80px;
transform: translate(-50%, -50%);
background-color: aqua;
}
2、用绝对定位+margin实现
将上面方法的Step2改用margin负宽和高的一半来实现
.child2 {
position: absolute;
width: 80px;
height: 80px;
background-color: rgb(127, 234, 255);
top: 50%;
left: 50%;
margin: -40px 0px 0px -40px; //盒子宽和高的一半为40px
}
3、通过方向值加margin实现
当盒子有宽和高时,利用绝对定位,设置四个方向的值都是0,并将margin的值设置为auto,实现水平和垂直方向居中.
通过设置四属性为0居中元素的做法有个前置条件,就是需要居中的盒子必须有固定的宽高(px),否则会失效。这就像四个方向有相同的力在拉这个盒子,配上margin:auto让这个盒子的位置保持中立,来达到盒子处于正中心的目的。
代码实现:
.child3 {
position: absolute;
width: 80px;
height: 80px;
background-color: aquamarine;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
4、flex布局实现
使用flex布局,通过align-items:center和justify-content:center设置容器的垂直和水平方向上为居中对齐,然后它的子元素也可以实现垂直和水平的居中。该方法要考虑兼容的问题
justify-content 设置弹性盒子中元素在主轴(横轴)方向上的对齐方式
align-items 设置弹性盒子中元素在侧轴(纵轴)方向上的对齐方式
注意:
依靠容器元素的属性,控制的是项目的排列方式,也就是说控制的不是自身,而是子元素
设置为flex布局以后,子元素的float,clear都失效了,换言之子元素不用浮动了,父元素也不用清除浮动了
设置了flex的元素,子元素会“块状化”。换言之,父元素使用了display:flex其子元素都会变成块级元素
代码实现:
.parent2 {
display: flex;
justify-content: center;
align-items: center;
background-color: antiquewhite;
height: 200px;
width: 200px;
}