盒子垂直居中+水平居中的需求時常常遇到的,看到的較多實現邏輯是固定content-box的寬度,經過讓margin-left和margin-top等於寬或高的負一半來實現,抑或不固定寬度,經過JS調整margin-left和margin-top的值,這倆種方法原理都同樣。
而我接下來要講的是content不定寬的狀況下,CSS的源生實現。html
主要利用td的vertical-align: middle;屬性實現垂直居中,固然你能夠用display:table-cell;也能夠獲得同樣的效果。配合margin: 0 auto;實現水平居中,支持IE 8+。
效果:https://codepen.io/FreadChen/...web
<style> *{ padding: 0; margin: 0; } html,body,.center-box{ height: 100%; width:100%; } .center-box>tr>td{ height: 100%; vertical-align: middle; } .content-box{ margin: 0 auto; /*下面這段是非必須的代碼,演示效果須要*/ background: #1f2d3d; width: 200px; height: 200px; } </style> <body> <table class="center-box"> <tr> <td> <div class="content-box"></div> </td> </tr> </table> </body>
利用flex佈局能夠實現更多功能,這裏利用了「justify-content」實現水平居中、「align-items」實現垂直居中,「flex: 0 0 auto;」讓元素保持原來的寬高。這個技術的侷限在於支持IE 10+。
瞭解Flex請戳:http://www.ruanyifeng.com/blo...
看效果請戳:https://codepen.io/FreadChen/...佈局
<style> *{ padding: 0; margin: 0; } html,body{ height: 100%; } .center-box{ display: -webkit-flex; /* Safari */ display: flex; /* // 水平居中 */ justify-content: center; /* // 垂直居中 */ align-items: center; height: 100%; width: 100%; } .content-box{ flex: 0 0 auto; width: 200px; height: 200px; background: #1f2d3d; } </style> <body> <div class="center-box"> <div class="content-box"></div> </div> </body>
利用position的絕對定位absolute(absolute的使用技巧自行了解)將left和top都設爲50%;再利用transform: translate(-50%,-50%);來補償元素寬高所帶來的位置影響。該技巧支持IE9+。
看效果請戳:https://codepen.io/FreadChen/...flex
<style> *{ padding: 0; margin: 0; } html,body,.center-box{ height: 100%; width:100%; } .content-box{ margin: 0 auto; /*下面這段是非必須的代碼,演示效果須要*/ background: #1f2d3d; width: 200px; height: 200px; position:absolute; left: 50%; top:50%; transform: translate(-50%,-50%); -ms-transform: translate(-50%,-50%); /* IE 9 */ -webkit-transform: translate(-50%,-50%); /* Safari and Chrome */ } </style> <body> <div class="content-box"></div> </body>