廢話很少說,直接上代碼:html
一、上中下佈局: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body { position: absolute; left: 0; right: 0; top: 0; bottom: 0; padding: 0; margin: 0; display: flex; flex-direction: column; } .header, .footer { height: 50px; } .body { flex-grow: 1; background-color: #DDD; } </style> </head> <body> <div class="header">Header</div> <div class="body">Content</div> <div class="footer">Footer</div> </body> </html>
顯示效果以下:
二、左右佈局:佈局
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body { position: absolute; left: 0; right: 0; top: 0; bottom: 0; padding: 0; margin: 0; display: flex; } .left, .right { height: 100%; } .left { width: 250px; background-color: rgba(255,0,0,0.3); } .right { display: flex; flex-direction: column; } .header, .footer { height: 50px; } .right, .content { flex-grow: 1; } .content { background-color: #DDD; } </style> </head> <body> <div class="left">LeftNav</div> <div class="right"> <div class="header">Header</div> <div class="content">Content</div> <div class="footer">Footer</div> </div> </body> </html>
頁面的效果以下:
flex
下面對幾個關鍵的樣式加以說明,這樣就能夠設計出任何想要的佈局了:spa
flex-grow: 1; // 表示容器在主軸的寬度有多餘時該子項佔據剩餘空間 position:absolute; left: 0;right: 0; top: 0; bottom: 0; // 這一組樣式讓該元素佔滿定位的父級元素