12-20 4,480 views
不管是PC页面还是移动端页面,经常会有弹出层菜单需要设计,用户的终端尺寸很多,怎样使弹出层或弹出元素在页面中水平和垂直居中呢?水平居中见的多,垂直居中该怎么写,下面给出本人用过的三种方法:
CSS:
- <html>
- <head>
- <style>
- body {
- margin: 0;
- padding: 0;
- width: 100%;
- height: 100%;
- display: table;
- }
- .container {
- text-align: center;
- display: table-cell;
- vertical-align: middle;
- }
- </style>
- </head>
- <body>
- <div class="container">
- 这是垂直居中的DIV
- </div>
- </body>
- </html>
vertical-align: middle 比较普通,缺点是不兼容IE9及更低版本的IE
CSS3:
- <html>
- <head>
- <style>
- body {
- margin: 0;
- padding: 0;
- }
- .container {
- top: 50%;
- left: 50%;
- position: absolute;
- transform: translate(-50%, -50%);
- }
- </style>
- </head>
- <body>
- <div class="container">
- 这是垂直居中的DIV
- </div>
- </body>
- </html>
transform: translate(x, y) 简单粗暴,IE9加上-ms-前缀即-ms-transform后可用,IE8及更低版本IE不支持
例子:上个月的手风琴图片轮换 http://wx.karlew.com/sfq/
JS:
- <html>
- <head>
- <style>
- body {
- margin: 0;
- padding: 0;
- }
- .container {
- width: 150px;
- margin: 0 auto;
- }
- </style>
- </head>
- <body>
- <div class="container" id="ctn">
- 这是垂直居中的DIV
- </div>
- </body>
- </html>
- <script>
- //原生代码可用jquery替代
- var vh = document.body.clientHeight;
- var obj = document.getElementById("ctn");
- var h = parseInt(obj.offsetHeight);
- obj.style.marginTop = (vh - h)*0.5;
- </script>
杀鸡也用牛刀,几乎所有浏览器都兼容,缺点是可能会影响前端性能