最近上课的时候学习了几种元素的居中方式,这里来总结一下
当然也可能不全,随便写一写
当元素没有固定的宽高的时候
1.transform
1.先对父元素元素进行绝对定位
2.然后对要居中的元素进行绝对定位,并且定位到top:50%,left:50%
3.最后用css3的元素变换,使这个元素相对于自己向上向左移动50%.element{
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
这种方法也适用于有宽高的元素
2.display: flex
给需要居中的元素的父元素设置弹性盒子.element{
display: flex;
justify-content; center;
align-item: center;
}
当元素有固定宽高的时候
假设这个元素宽高都是100px
1. 绝对定位和负外边距
1.给父元素设置相对定位
2.给子元素设置绝对定位,left: 50%,top: 50%
3.给子元素设置负的上,左外边距.element{
position: absolute;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -50px;
}
或者使用css计算函数calc().element{
position: absolute;
left: calc(50% - 50px);
top: calc(50% - 50px) ;
}
2. 绝对定位和margin: auto
1.给居中元素设置绝对定位,left,right,top,bottom 都设置为0
2.设置margin: auto.element{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}