div水平垂直居中方法总汇
方法一:
绝对定位方法:不确定当前div的宽度和高度,采用transform:translate(-50%,-50%);当前div的父级添加相对定位(position:relative)
.Children{
background: aqua;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
方法二:
绝对定位方法:确定当前div宽度和高度吗,margin值为当前div宽度一半的负值。
.Children{
width: 200px;
height: 200px;
background: aqua;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
方法三:
绝对定位方法:绝对定位下top left right bottom都设置为0,margin为auto
width: 50px;
height: 50px;
background: aqua;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
方法四:
flex布局
.Father{
height: 200px;
width: 200px;
background-color: orangered;
display: flex;
justify-content: center;
align-items: center;
}
.Children{
width: 50px;
height: 50px;
background: aqua;
}
方法五:
table-cell 和middle、center组合使用
.Father{
height: 200px;
width: 200px;
background-color: orangered;
display: table-cell;
vertical-align: middle;
text-align: center;
}
方法六:
绝对定位:calc函数动态计算
.Father{
height: 200px;
width: 200px;
background-color: orangered;
position: relative;
}
.Children{
width: 50px;
height: 50px;
background: aqua;
position: absolute;
left: calc((200px-50px)/2) ;
top: calc((200px-50px)/2) ;
}