盒子垂直居中+水平居中的需求时常常遇到的,看到的较多实现逻辑是固定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>