1、flex布局方法
- 父元素设置flex属性: 可以实现子元素水平垂直居中效果
div{
display:flex;
justify-content:center; //设置水平居中
align-items:center; //设置垂直居中
}
- 父元素设置flex,子元素设置margin:0 auto;
.father{
display:flex
}
.son{
margin:0 auto; //可实现子元素居中对齐
}
2、子绝父相
.father{
position:relative;
}
.son{
position:absolute;
top: 50%; //将元素的顶部定位到父容器的50%
left: 50%; //将元素的左侧定位到父容器的50%
transform: translate(-50%, -50%); //平移元素的50%自身尺寸,从而实现居中效果
}
详解transform:
概念:
transform 是CSS属性,用于应用一些变换效果(如平移、缩放、旋转等)到元素上。translate() 是transform 属性的一个函数,用于平移元素。通过给 translate() 函数提供水平和垂直的偏移百分比,可以将元素相对于自身的尺寸进行平移,从而实现水平和垂直居中
基本过程:
- 1
- 2
- 3
- 4
完美解决~~~