div適應螢幕垂直居中的多種解決方案
阿新 • • 發佈:2018-11-27
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> *{margin: 0;padding: 0;font-size: 20px} /*方法一 div使用絕對佈局 position:absolute; top left right button的值一樣,不一定都為0;margin:auto;*/ .main{ width: 200px; height: 200px; background-color: #00b7ee; position: absolute; top:0; left: 0; right: 0; bottom:0; margin: auto; text-align: center; line-height: 180px; } /*方法二 絕對佈局,讓left和top都是50%,這在水平方向上讓div的最左與螢幕的最左相距50%,垂直方向上一樣,所以再用transform向左(上)平移它自己寬度(高度)的50%,也就達到居中效果了*/ .main{ width: 200px; height: 200px; background-color: #00b7ee; position: absolute; top:50%; left: 50%; transform: translate(-50%,-50%); text-align: center; line-height: 180px; } /*方法三 絕對佈局,讓left和top都是50%,margin: -100px 0 0 -100px;*/ .main{ width: 200px; height: 200px; background-color: #00b7ee; position: absolute; top:50%; left: 50%; margin: -100px 0 0 -100px; text-align: center; line-height: 180px; } /*方法四 flex佈局*/ body{ width: 100%; height: 100vh;/**螢幕高度百分百*/ display: flex; align-items:center; justify-content:center; } .main{ border: 1px solid #0000FF; height: 200px; width: 400px; display: flex; align-items:center; justify-content:center; } </style> </head> <body> <div class="main"> <h1 class="h11">MAIN</h1> </div> </body> </html>