開門見山,以下內容主要以較為常見的三欄布局(左右固定寬度,中間寬度自適應)作為模版來跟大家分享。本文分享五種較為常用的布局方式,如果有其他方式方法的歡迎評論區交流。作為一年開發的前端小白,還請各位技術大佬發現問題請指正,歡迎交流,勿罵😂。
浮動布局、絕對定位布局、flexbox布局、表格布局、網格布局;
1、浮動布局
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>三欄布局</title> <style> html * { margin: 0; padding: 0; } .box div { min-height: 100px; } .box .left { float: left; width: 300px; background: red; } .box .right { float: right; width: 300px; background: blue; } .box .center { background: green; } </style> </head> <body> <div class="box"> <div class="left"><p>left</p></div> <div class="right"><p>right</p></div> <div class="center"><p>center</p></div> // 使用浮動布局時候請注意center DIV所在位置,如果該DIV寫在中間樣式會存在問題; </div> </body> </html>
2、絕對定位布局
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>絕對定位布局</title> <style> html * { margin: 0; padding: 0; } .box div { min-height: 100px; position: absolute; } .box .left { left: 0; width: 300px; background: red; } .box .right { right: 0; width: 300px; background: blue; } .box .center { left: 300px; right: 300px; background: green; } </style> </head> <body> <div class="box"> <div class="left"><p>left</p></div> <div class="center"><p>center</p></div> <div class="right"><p>right</p></div> </div> </body> </html>
3、flexbox布局
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>flexbox布局</title> <style> html * { margin: 0; padding: 0; } .box { display: flex; min-height: 100px; } .box .left { width: 300px; background: red; } .box .right { width: 300px; background: blue; } .box .center { flex: 1; background: green; } </style> </head> <body> <div class="box"> <div class="left"><p>left</p></div> <div class="center"><p>center</p></div> <div class="right"><p>right</p></div> </div> </body> </html>
4、表格布局
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表格布局</title> <style> html * { margin: 0; padding: 0; } .box { width: 100%; display: table; min-height: 100px; } .box div { display: table-cell; } .box .left { width: 300px; background: red; } .box .right { width: 300px; background: blue; } .box .center { background: green; } </style> </head> <body> <div class="box"> <div class="left"><p>left</p></div> <div class="center"><p>center</p></div> <div class="right"><p>right</p></div> </div> </body> </html>
5、網格布局
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>網格布局</title> <style> html * { margin: 0; padding: 0; } .box { width:100%; display: grid; grid-template-rows: 100px; grid-template-columns: 300px auto 300px; } .box .left { background: red; } .box .right { background: blue; } .box .center { background: green; } </style> </head> <body> <div class="box"> <div class="left"><p>left</p></div> <div class="center"><p>center</p></div> <div class="right"><p>right</p></div> </div> </body> </html>
以上五種布局方式都是基於網頁高度固定的情況,實現左右固定中間自適應的布局。
