例
| 代碼如下 |
複製代碼 |
<!doctype html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>左欄固定寬度,右欄自適應之絕對位置法</title> <style type="text/css"> body{ margin: 0; } #nav{ top: 0; left: 0; width: 230px; height: 600px; background: #ccc; position: absolute; } #main{ height: 600px; margin-left: 230px; background: #0099ff; } </style> </head> <body> <div id="container"> <div id="nav"> 左欄 </div> <div id="main"> 右欄 </div> </div> </body> </html> |
看起來很美好,但是。。
由於左欄使用絕對位置,脫離了文檔流,因此有一個缺陷,即當左欄高度大於右欄時,無法將container撐開,這個缺陷單單只看兩欄布局並沒有太大影響,但如果兩欄布局下面有一個底欄,就會出現底欄與左欄重疊的情況:
| 代碼如下 |
複製代碼 |
<!doctype html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>左欄固定寬度,右欄自適應之絕對位置法</title> <style type="text/css"> body{ margin: 0; } #nav{ top: 0; left: 0; width: 230px; height: 600px; background: #ccc; position: absolute; } #main{ height: 400px; margin-left: 230px; background: #0099ff; } #footer{ text-align: center; background: #009000; } </style> </head> <body> <div id="container"> <div id="nav"> 左欄 </div> <div id="main"> 右欄 </div> </div> <div id="footer"> 底欄 </div> </body> </html> |
我們再來看看第二種方法,左欄固定寬度,右欄自適應之負margin法:
| 代碼如下 |
複製代碼 |
<!doctype html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>左欄固定寬度,右欄自適應之負margin法</title> <style type="text/css"> body{ margin: 0; } #container{ margin-left: 230px; _zoom: 1; /*相容IE6下左欄消失問題*/ } #nav{ float: left; width: 230px; height: 600px; background: #ccc; margin-left: -230px; position: relative; /*相容IE6下左欄消失問題,IE6真不讓人省心啊>_<*/ } #main{ height: 600px; background: #0099ff; } </style> </head> <body> <div id="container"> <div id="nav"> 左欄 </div> <div id="main"> 右欄 </div> </div> </body> </html> |
這樣無論兩欄的高度如何變化都不會有問題了:
| 代碼如下 |
複製代碼 |
<!doctype html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>左欄固定寬度,右欄自適應之負margin法</title> <style type="text/css"> body{ margin: 0; } #container{ margin-left: 230px; _zoom: 1; /*相容IE6下左欄消失問題*/ } #nav{ float: left; width: 230px; height: 600px; background: #ccc; margin-left: -230px; position: relative; /*相容IE6下左欄消失問題,IE6真不讓人省心啊>_<*/ } #main{ height: 400px; background: #0099ff; } #footer{ clear: both; text-align: center; background: #009000; } </style> </head> <body> <div id="container"> <div id="nav"> 左欄 </div> <div id="main"> 右欄 </div> </div> <div id="footer"> 底欄 </div> </body> </html> |