不管是PC页面还是移动端页面,经常会有弹出层菜单需要设计,用户的终端尺寸很多,怎样使弹出层或弹出元素在页面中水平和垂直居中呢?水平居中见的多,垂直居中该怎么写,下面给出本人用过的三种方法:

 

CSS:

  1. <html>
  2. <head>
  3. <style>
  4. body {
  5.     margin: 0;
  6.     padding: 0;
  7.     width: 100%;
  8.     height: 100%;
  9.     display: table;
  10. }
  11.     .container {
  12.     text-aligncenter;
  13.     displaytable-cell;
  14.     vertical-alignmiddle;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19.     <div class="container">
  20.         这是垂直居中的DIV
  21.     </div>
  22. </body>
  23. </html>

 

vertical-align: middle 比较普通,缺点是不兼容IE9及更低版本的IE

 

CSS3:

  1. <html>
  2. <head>
  3. <style>
  4. body {
  5.     margin: 0;
  6.     padding: 0;
  7. }
  8. .container {
  9.     top: 50%;
  10.     left: 50%;
  11.     positionabsolute;
  12.     transform: translate(-50%, -50%);
  13. }
  14. </style>
  15. </head>
  16. <body>
  17.     <div class="container">
  18.         这是垂直居中的DIV
  19.     </div>
  20. </body>
  21. </html>

 

transform: translate(x, y) 简单粗暴,IE9加上-ms-前缀即-ms-transform后可用,IE8及更低版本IE不支持

例子:上个月的手风琴图片轮换 http://wx.karlew.com/sfq/

 

JS:

  1. <html>
  2. <head>
  3. <style>
  4. body {
  5.     margin: 0;
  6.     padding: 0;
  7. }
  8. .container {
  9.     width: 150px;
  10.     margin: 0 auto;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15.     <div class="container" id="ctn">
  16.         这是垂直居中的DIV
  17.     </div>
  18. </body>
  19. </html>
  20. <script>
  21.     //原生代码可用jquery替代
  22.     var vh = document.body.clientHeight;
  23.     var obj = document.getElementById("ctn");
  24.     var h = parseInt(obj.offsetHeight);
  25.     obj.style.marginTop = (vh - h)*0.5;
  26. </script>

 

杀鸡也用牛刀,几乎所有浏览器都兼容,缺点是可能会影响前端性能

欢迎留言