原文地址:https://blog.youkuaiyun.com/alitterboy/article/details/54587890
1,绝对定位的方法
.box{
width: 500px;
height: 600px;
border: 1px solid #666;
position: relative;
}
.con{
width: 100px;
height: 100px;
position: absolute;
background-color: red;
left: 50%;
top: 50%;
/*元素宽度一半*/
margin-left: -50px;
/*元素高度一半*/
margin-top: -50px;
}
html代码
<div class="box">
<div class="con"></div>
</div>
结果如上图所示。可以实现在父容器内的居中效果。
优点:
1,所有的浏览器都是支持的。
缺点:
其必须是固定宽高的,其宽高是不可以变得。适用范围比较窄。
2,固定定位方法
div{
width:100px;
height:100px;
position:fixed;
left:50%;
top:50%;
margin-left:-50px;
margin:top:-50px;
}
这种实现的方法和第一种方法思路是一样的。优缺点也是一样的。
3,绝对定位加margin:auto实现
div{
position:absolute;
width:100px;
height:100px;
margin:auto;
left:0;
top:0;
right:0;
bottom:0;
}
这种实现方式比较灵活。但其在ie低版本的时候是不支持的。在标准的浏览器下,可以随意使用。
4,固定定位加margin:auto实现
div{
position:fixed;
width:100px;
height:100px;
margin:auto;
left:0;
top:0;
right:0;
bottom:0;
}
同样的将绝对定位换成固定定位,也是可以实现的。
5,table-cell实现
.box{
width: 300px;
height: 300px;
display: table-cell;
vertical-align: middle;
text-align: center;
border:1px solid #000;
}
.box div{
width:100px;
height:100px;
margin 0 auto;
background-color: red;
}
<div class="box">
<div></div>
</div>
这种方法有其局限性。
1,其父元素或子元素不可以出现浮动。
2,子元素是行内元素的时候可以不加”margin:0 auto;”这一句。如果是块级元素,就必须要加这一句代码。
6,针对行内元素
div{
height:100px;
text-align:center;
line-height:100px;
}
这种只针对行内元素有效。
7,利用css3的属性
div{
display:flex;
justify-content:center;
align-items:center;
}
这种是利用css3的弹性盒模型。优点是简单,适用性广。缺点是低版本的浏览器不支持。
8,利用css3的transform属性
.box {
width: 300px;
height: 300px;
position: relative;
}
.box div{
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
background-color: red;
}
<div class="box">
<div></div>
</div>
其实这种和第一种的原理是一样的。但比第一种的局限性小很多。缺点就是低版本的浏览器是不支持的。