div水平垂直居中
第一种:
使用绝对定位,确定div的宽高,margin分别为div宽高的一半负值(父级相对定位)
代码:
div {
width: 400px;
height: 400px;
background: blue;
position: absolute;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -200px;
}
第二种:
使用绝对定位,不用确定div宽高,使用css中的transform属性进行实现(父级相对定位)
代码:
div{
background: blue;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
第三种:
使用绝对定位,设置top,right,bottom,left为0(父级相对定位)
代码:
div{
width: 600px;
height: 600px;
background: blue;
position:absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
第四种:
使用flex布局(结合父级一起用)
代码:
html:
<div class="parent">
<div class="child">child</div>
</div>
css:
.parent{
height: 600px;
-webkit-display: flex;
display: flex;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
border: 1px solid #ddd;
}
.child{
width: 400px;
height: 400px;
background-color: blue;
}
第五种:
使用table-cell实现水平垂直居中: table-cell middle center组合使用
代码:
html:
<div class="table-cell">
<p>盒子</p>
</div>
css:
.table-cell {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 320px;
height: 200px;
border:1px solid #ddd;
}
第六种:
使用绝对定位,通过calc() 函数动态计算实现
代码:
html:
<div class="parent">
<div class="child">child</div>
</div>
css:
.parent {
position: relative;
border: 1px solid #eee;
width: 500px;
height: 300px;
}
.parent .child{
position: absolute;
width: 200px;
height: 100px;
left: -webkit-calc((500px - 200px)/2);
top: -webkit-calc((300px - 100px)/2);
left: -moz-calc((500px - 200px)/2);
top: -moz-calc((300px - 100px)/2);
left: calc((500px - 200px)/2);
top: calc((300px - 100px)/2);
}
以上效果可自行复制代码到编辑器运行即可!
希望大佬看到有不对的地方,提出博主予以改正!

浙公网安备 33010602011771号