【前端攻城獅之路】CSS兩列布局——右側固定寬度、左側自適應
阿新 • • 發佈:2019-02-20
做了一道貓廠很經典的前端筆試題,解決了一直以來在兩列布局的認識上思考太少的毛病。
題目要求是右側aside固定寬度200px,左側content自適應。
本來直接用float,發現aside總是會被“擠”到content以下、footer以上的位置,debug了好久最終還是看了大牛的部落格才意識到這個問題所在。
基本思路是:
①content寬度不設,讓它預設auto,設一下高度(好看)
②aisde在右邊那就 float:right ,設定固定寬度200px
③重點!!給content設定aside方向(本題右)上的maigin,且margin值要足夠放下aside
④超重點,也是坑人的地方!!!把body中代表aside的div提到content這個div的前面,這樣瀏覽器渲染content的時候它就正好“疊”到了aside的左邊距上,完美並排!
效果圖
實現程式碼
(不同螢幕不同瀏覽器效果不同,未做多瀏覽器相容,僅供參考思路)
body{ margin: 0; padding: 0 5px; } #header{ width: 100%; height: 18%; border: green 1px solid; margin-bottom: 1%; } #logo{ width: 80px; height: 80px; border: red 1px solid; float: left; margin-top: 20px; margin-left: 20px; } #username{ width: 200px; height: 30px; border: black 1px solid; float: right; margin-top: 75px; margin-right: 20px; text-align: right; } #main{ overflow: hidden; } #content{ height: 430px; border: blue 1px solid; margin-right: 240px; } #aside{ width: 200px; height: 30px; border: red 1px solid; float: right; } #footer{ width: 100%; height: 9%; border: black 1px solid; clear: both; margin-top: 1%; }
<html> <head> <title>兩列布局--右側定寬左側自適應</title> <link rel="stylesheet" type="text/css" href="right200px_and_leftauto.css"> </head> <body> <div id="header"> <div id="logo">Logo</div> <div id="username">使用者名稱</div> </div> <div id="main"> <div id="aside">aside-固定寬度200px</div> <div id="content">content-寬度自適應</div> </div> <div id="footer">footer</div> </body> </html>