今天看到一道面试题,怎么样一个div水平垂直居中,当时想到的就是绝对定位+top和left,却忘了再经过margin进行修正,因而拿出css权威指南,从新复习了下定位的知识,写个总结:css
一.水平居中css3
<style> #box{ width: 300px; height: 200px; border: solid black; background-color: bisque; margin: 0 auto; } </style> <div id="box"></div>
auto:浏览器根据剩余空间自动定位距离,当左右都设置为auto的时候,保证左右剩余空间相同,就变成了居中。要注意的是:只对左右设置有用,上下没用,因此不能经过这种方式达到垂直居中目的。面试
二.水平垂直居中浏览器
方式1:code
<style> #box{ width: 300px; height: 200px; border: solid black; background-color: bisque; position: absolute; top:0; right: 0; bottom: 0; left: 0; margin:auto; } </style> <div id="box"></div>
首先position绝对定位,再把top right bottom left都巧妙设置成0,最后设置margin为auto,浏览器就自动在div上下和左右都留下相等的间距,达到了水平和垂直都居中的目的。orm
方式2:it
<style> #box{ width: 300px; height: 200px; border: solid black; background-color: bisque; position: absolute; top:50%; left:50%; margin-top:-100px; /*高度的一半*/ margin-left: -150px;/*宽度的一半*/ } </style> <div id="box"></div>
top和left都是针对div左上角那个点定位的,因此都设置了50%,至关于把div左上角那个点定位到了浏览器正中间,再经过margin-top和margin-left修正位置。io
方式3:form
<style> #box{ width: 300px; height: 200px; border: solid black; background-color: bisque; position: absolute; top:50%; left:50%; transform: translate(-50%,-50%); } </style> <div id="box"></div>
原理与方式二相同,不一样点在于利用css3里面的transform属性进行位置的修正原理
若是还有其余经常使用的方式,欢迎在文章下面留言补充,谢谢