轉載來源:https://blog.csdn.net/cristina_song/article/details/78374705
1,固定寬度區浮動,自適應區不設寬度而設置 margin
<!DOCTYPE html> <html> <head> <style type="text/css"> #wrap { overflow: hidden; *zoom: 1; } #content ,#sidebar { background-color: #eee; } #sidebar { float: left; width: 300px; } #content { /*float: right;此處不能寫浮動,否則會脫離文檔流*/ margin-left: 310px; } #footer {background-color: #f00;color:#fff; margin-top: 1em} </style> </head> <body> <div id="wrap"> <div id="sidebar" style="height:340px;">固定寬度區</div> <div id="content" style="height:340px;">自適應區</div> </div> <div id="footer">後面的一個DIV,以確保前面的定位不會導致後面的變形</div> </body> </html>
無論content和sidebar誰更長,都不會對佈局造成影響.
2,固定寬度區使用絕對定位,自適應區照例設置margin
<!DOCTYPE html> <html> <head> <style type="text/css"> #wrap { *zoom: 1; position: relative; } #content ,#sidebar { background-color: #eee; } #sidebar {position: absolute; left:0; top: 0;width: 300px; } #content { margin-left: 310px; } #footer {background-color: #f00;color:#fff; margin-top: 1em} </style> </head> <body> <div id="wrap"> <div id="sidebar" style="height:340px;">固定寬度區</div> <div id="content" style="height:240px;">自適應區</div> </div> <div id="footer">後面的一個DIV,以確保前面的定位不會導致後面的變形</div> </body> </html>
footer說——我不給絕對主義者讓位!所以要注意footer的設置。
3.標準瀏覽器的方法
w3c標準早就爲我們提供了製作這種自適應寬度的標準方法。那就簡單了:把wrap設爲display:table並指定寬度100%,然後把content+sidebar設爲display:table-cell;然後只給sidebar指定一個寬度,那麼content的寬度就變成自適應了。
<!DOCTYPE html> <html> <head> <style type="text/css"> #wrap { display:table; width: 100%; } #content,#sidebar { background-color: #eee; display: table-cell; } #sidebar { width: 300px; } #content { margin-left: 10px; display: block; } #footer {background-color: #f00;color:#fff; margin-top: 1em} </style> </head> <body> <div id="wrap"> <div id="sidebar" style="height:240px;">固定寬度區</div> <div id="content" style="height:340px;">自適應區</div> </div> <div id="footer">後面的一個DIV,以確保前面的定位不會導致後面的變形</div> </body> </html>
如果不考慮ie7及以下版本,則使用標準方法;如果不在意sidebar與content的順序,則用第一種方法;