div{ width:100px; height:100px; position:absolute; left:50%; top:50%; margin-left:-50px; margin:top:-50px; }
结果如上图所示。可以实现在父容器内的居中效果。
优点:
1,所有的浏览器都是支持的。
缺点:
其必须是固定宽高的,其宽高是不可以变得。适用范围比较窄。
div{ width:100px; height:100px; position:fixed; left:50%; top:50%; margin-left:-50px; margin:top:-50px; }
这种实现的方法和第一种方法思路是一样的。优缺点也是一样的。
div{ position:absolute; width:100px; height:100px; margin:auto; left:0; top:0; right:0; bottom:0; }
这种实现方式比较灵活。但其在ie低版本的时候是不支持的。在标准的浏览器下,可以随意使用。
div{ position:fixed; width:100px; height:100px; margin:auto; left:0; top:0; right:0; bottom:0; }
同样的将决定定位换成固定定位,也是可以实现的。
.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;”这一句。如果是块级元素,就必须要加这一句代码。
div{ height:100px; text-align:center; line-height:100px; }
这种只针对行内元素有效。
div{ display:flex; justify-content:center; align-items:center; }
这种是利用css3的弹性盒模型。优点是简单,适用性广。缺点是低版本的浏览器不支持。
.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>
其实这种和第一种的原理是一样的。但比第一种的局限性小很多。缺点就是低版本的浏览器是不支持的。