[英]css flexible middle column layout
如何使.col2
靈活,以便填充.col1
和.col3
之間的空間。 我嘗試了百分號,但沒有用。 實現此目標的最佳方法是什么? 謝謝。
body{ margin:0; } .header{ width:100%; background:gray; height:120px; margin:0 auto; } .MainController{ width:100%; clear:both; } .col1{ height:679px; background:yellow; width:150px; float:left; } .col2{ height:679px; background:black; float:left; width:20%; } .col3{ height:679px; background:red; width:300px; float:right; }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="header"></div> <div class="MainController"> <div class="col1"></div> <div class="col2"></div> <div class="col3"></div> </div> </body> </html>
您可以使用Flexbox
布局。 將display: flex
應用於父對象,並將flex: 1
添加到.col2
以使其動態擴展。
body { margin: 0; } .header { width: 100%; background: gray; height: 120px; margin: 0 auto; } .MainController { width: 100%; clear: both; display: flex; } .col1 { height: 679px; background: yellow; width: 150px; } .col2 { flex: 1; background: black; width: 20%; } .col3 { background: red; width: 300px; }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="header"></div> <div class="MainController"> <div class="col1"></div> <div class="col2"></div> <div class="col3"></div> </div> </body> </html>
calc
: 您可以使用calc
計算寬度。 .col2
將是寬度的100%減去兩列的寬度。 因此,在這種情況下:
calc: (100% - 450px); /*150px + 300px = 450px*/
您的代碼變為:
body{ margin:0; } .header{ width:100%; background:gray; height:120px; margin:0 auto; } .MainController{ width:100%; clear:both; } .col1{ height:679px; background:yellow; width:150px; float:left; } .col2{ height:679px; background:black; float:left; width:calc(100% - 450px); } .col3{ height:679px; background:red; width:300px; float:right; }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="header"></div> <div class="MainController"> <div class="col1"></div> <div class="col2"></div> <div class="col3"></div> </div> </body> </html>
flexbox
: 您也可以像Aziz建議的那樣使用flexbox
。
只需將.col2
設置為flex:1
,將.MainController
為display:flex
。 像這樣:
body{ margin:0; } .header{ width:100%; background:gray; height:120px; margin:0 auto; } .MainController{ width:100%; clear:both; display: flex; } .col1{ height:679px; background:yellow; width:150px; float:left; } .col2{ height:679px; background:black; float:left; flex: 1; } .col3{ height:679px; background:red; width:300px; float:right; }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="header"></div> <div class="MainController"> <div class="col1"></div> <div class="col2"></div> <div class="col3"></div> </div> </body> </html>
兩種方法都得到廣泛支持,但是您可能仍要在此處檢查瀏覽器支持。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.