下面總結了四中方法,使用時將相應的註釋去掉就能夠了html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> html, body { margin: 0px; padding: 0px; } /*不定寬高的彈出框!!!!*/ /*方法一:fixed + translate負百分比實現*/ /*IE10纔開始支持*/ /*.div1{ display:inline-block; background-color: cornflowerblue; position: fixed; left: 50%; top: 50%; transform: translate(-50%,-50%); }*/ /*方法二:flex佈局,兼容性更差*/ /*IE11+*/ /*html,body{ height: 100%; } .container{ min-height: 100%; display: flex; justify-content: center; align-items: center; } .div1 { display: inline-block; background-color: cornflowerblue; }*/ /*table佈局*/ /*方法三:利用text-align、vertical-align實現,兼容性強!*/ html, body { height: 100%; } .container { height: 100%; text-align: center; } .container:before { content: ""; display: inline-block; vertical-align: middle; height: 100%; } .div1 { display: inline-block; background-color: cornflowerblue; vertical-align: middle; } /*方法四:vw、vh結合table-cell,IE9+兼容*/ /*html, body { height: 100%; } .container { height: 100vh; width: 100vw; display: table-cell; text-align: center; vertical-align: middle; } .div1 { display: inline-block; background-color: cornflowerblue; }*/ </style> </head> <body> <div class="container"> <div class="div1"> <p>hhhhhhhhhhhh</p> <p>jjjjj</p> <p>kkkkkkkkkkkkkkk</p> <p>kkkkkkkkkkkkkkk</p> <p>kkkkkkkkkkkkkkk</p> <p>kkkkkkkkkkkkkkk</p> </div> </div> </body> </html>