1、flex布局方法:当前div的父级添加flex css样式
display: flex;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
2、绝对定位方法:不确定当前div的宽度和高度,采用 transform: translate(-50%,-50%); 当前div的父级添加相对定位(position: relative;)
background: green;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
3、绝对定位方法:确定了当前div的宽度,margin值为当前div宽度一半的负值
.father {
background: red;
position: relative;
width: 500px;
height: 500px;
}
.son {
width: 200px;
height: 200px;
background: green;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
4、绝对定位方法:绝对定位下top left right bottom 都设置0 ,margin设置为auto
.father {
background: red;
position: relative;
width: 500px;
height: 500px;
}
.son {
width: 200px;
height: 200px;
background: green;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
5、table-cell实现水平垂直居中: table-cell middle center组合使用(子元素不能是块级元素) 子div只能不能是块状元素,否则只能垂直居中,无法水平居中
/*table-cell、vertical-align、text-align组合使用*/
.father {
width: 500px;
height: 500px;
display: table-cell;
vertical-align: middle;
text-align: center;
background-color: red;
}
.son {
width: 200px;
height: 200px;
background-color: green;
display: inline-block;