1、定位+偏移
需要用到position: relative;
position: absolute;
transform: translate();
.about{
width: 100%;
height: 600px;
margin: 20px auto 0;
position: relative;
background: aquamarine;
.box{
width: 200px;
height: 200px;
background: red;
position: absolute;
left:50%;
top:50%;
transform: translate(-50%,-50%);
}
}
效果:
分析:
通过定位可以使子级div左上角在父级div的中心,这是会发现我们位置移动过多,需要将回退自身的宽度和高度的一半,即可达到我们的效果,即需要同用到transform: translate(-50%,-50%);这个方法是博主使用最多的,博主推荐这个方法。
2、间距
需要用到padding:;
margin:;
calc()
box-sizing: border-box;
.about{
width: 100%;
height: 600px;
margin-top: 20px;
background: aquamarine;
padding: calc( (600px - 200px) * 0.5 ) 0 0 calc( (100% - 200px) * 0.5);
box-sizing: border-box;
.box{
width: 200px;
height: 200px;
background: red;
}
}
效果:
分析:
这里是纯用内边距的,会将我们设置的大小撑起来,所以为了不影响我们自己设置的大小,需要设置box-sizing: border-box;让大小固定。之后就是让子级div移动父级div宽高减去子级div宽度的一半即可。但由于此方法会用到父子div的大小,无法应对全部情况。所以博主不推荐使用这个方法。
.about{
width: 100%;
height: 600px;
margin-top: 20px;
background: aquamarine;
padding: calc( (600px - 200px) * 0.5 ) 0 0 0;
box-sizing: border-box;
.box{
width: 200px;
height: 200px;
background: red;
margin: 0 auto;
}
}
这里是外边距和内边距混用,主要是水平方向采用margin: 0 auto;其他不变。
3、flex布局
需要用到display: flex;
.about{
width: 100%;
height: 600px;
margin-top: 20px;
background: aquamarine;
display: flex;
flex-flow: column;
align-items: center;
justify-content: center;
.box{
width: 200px;
height: 200px;
background: red;
}
}
效果:
分析:
flex-flow: column;在flex布局中为设置主轴方向,有column和row两个值,默认以row为主轴,其中column以垂直方向为主轴,row以水平方向为主轴。
align-items: center;是使副轴方向居中对齐。
justify-content: center;是设置主轴内容相对于空隙居中分布。
博主推荐。但可能会存在兼容性问题。
4、grid布局
需要用到:display: grid;
.about{
width: 100%;
height: 600px;
margin-top: 20px;
background: aquamarine;
display: grid;
place-items: center;
.box{
width: 200px;
height: 200px;
background: red;
}
}
效果:
分析
grid布局和flex布局在属性上内容差不多,只是justify-items在flex布局中不起效果但在grid会起效果。这里的place-items: center;其实是align-items: center; justify-items: center;的结合。另外grid不需要设置主轴方向。这个方法也是博主目前发现最简洁的方法。也是新学到的,推荐使用。但可能会存在兼容性问题。
5、定位+外边距
需要用到position: relative;
position: absolute;
margin: auto;
.about{
width: 100%;
height: 600px;
margin: 20px auto 0;
position: relative;
background: aquamarine;
.box{
width: 200px;
height: 200px;
background: red;
position: absolute;
left:0;
top:0;
right:0;
bottom: 0;
margin: auto;
}
}
效果
分析:
一般子级div是否在父级div里面居中都是需要计算的,如果父元素的宽度是200px,子元素的宽度是100px,公式:父元素的宽度=子元素的宽度+padding+margin+border(w3c标准盒子模型) ,这里子元素没有padding,border,那么子元素的外边距margin应该是(200-100)/2=50px ,如果子元素直接设置margin:auto,那么这个auto就是50px,所以这种居中是靠外边距margin-left 和margin-right来实现居中的,为什么垂直居中应该w3c默认规定margin-top和margin-right为0,所以实现不了垂直居中,但是绝对定位可以,在绝对定位之后如果设置了margin:auto,那么margin-top和margin-right不再为默认的0,而是auto,从而在已经实现了水平居中的情况下进而实现了水平垂直居中!这是博主刚刚新学到的方法,推荐使用。