纯css控制让一个div水平垂直居中的6种方法

注意相对父级定位:

方法一:
 div{
width: 200px;
height: 200px;
background: green;
position:absolute;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}

方法二:常用()

div{
width:200px;
height: 200px;
background:green;
position: absolute;
left:50%;
top:50%;
margin-left:-100px;
margin-top:-100px;
}

方案三:

div绝对定位水平垂直居中【Transforms 变形】

兼容性:IE8不支持;

div{
width: 200px;
height: 200px;
background: green;
position:absolute;
left:50%; /* 定位父级的50% */
top:50%;
transform: translate(-50%,-50%); /*自己的50% */
}

方案四:

css不定宽高水平垂直居中

.box{

height:600px;
display:flex;
justify-content:center;
align-items:center;
/* aa只要三句话就可以实现不定宽高水平垂直居中。 */
}
.box>div{
background: green;
width: 200px;
height: 200px;
}


方案五

将父盒子设置为table-cell元素,可以使用text-align:center和vertical-align:middle实现水平、垂直居中。
比较完美的解决方案是利用三层结构模拟父子结构



tableCell






/*
table-cell实现居中
将父盒子设置为table-cell元素,设置
text-align:center,vertical-align: middle;
子盒子设置为inline-block元素
*/
.tableCell{
display: table;
}
.tableCell .ok{
display: table-cell;
text-align: center;
vertical-align: middle;
}
.tableCell .innerBox{
display: inline-block;
}

方案六:

对子盒子实现绝对定位,利用calc计算位置


calc



/*绝对定位,clac计算位置*/
.calc{
position: relative;
}
.calc .innerBox{
position: absolute;
left:-webkit-calc((500px - 200px)/2);
top:-webkit-calc((120px - 50px)/2);
left:-moz-calc((500px - 200px)/2);
top:-moz-calc((120px - 50px)/2);
left:calc((500px - 200px)/2);
top:calc((120px - 50px)/2);
}

转载于:https://www.cnblogs.com/YuFengAoTian/p/8204084.html

你可能感兴趣的:(纯css控制让一个div水平垂直居中的6种方法)