最近剛剛面試 ,面試題中有個左邊定寬,右邊自適應兩列布局,我寫完了面試官問我,這樣能夠嗎?我說應該能夠吧,其實我也不知道,回來後敲代碼,驗證,果真,我答錯了,而後經過個人不懈努力,終於,你懂的。。。下面我把代碼附上css
這道題,看起來很簡單,其實否則,小弟不才,想出了三種方法能夠實現html
第一:採用浮動元素,固然也得清浮動嘍,左邊浮動,右邊用margin-left,,看淡word-break:break-all了沒,是強制讓內容換行,要不就跑遠了。。。面試
<!doctype html> <html> <head> <meta charset="utf-8"> <title>左側定寬,右側自適應(1)</title> <style type="text/css"> *{margin: 0;padding: 0;} div.contain{overflow: auto;zoom:1; background: yellow;} div.left{float: left;width: 200px;height: 400px;background: red; word-break: break-all;} div.right{margin-left:200px; height: 400px; background: blue; word-break: break-all;} </style> </head> <body> <div class="contain"> <div class="left"><p>2222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222</p> </div> <div class="right"> 11111111111111111111111111111111 11111111111111111111111111111111 11111111111111111111111111111111 11111111111111111111111111111111 </div> </div> 123 </body> </html>
第二種:用相對定位,左邊用position:absolute,右邊用margin-left,其實跟浮動定位差很少,不過我也貼出來佈局
<!doctype html> <head> <meta charset="utf-8"> <title>左側定寬,右側自適應(2)</title> <style type="text/css"> *{margin: 0;padding: 0;} div.contain{overflow: auto;zoom:1; background: yellow; position: relative;} div.left{ position: absolute; left: 0;top: 0; width: 200px;height: 400px;background: red; word-break: break-all;} div.right{margin-left:200px; height: 400px; background: blue; word-break: break-all;} </style> </head> <body> <div class="contain"> <div class="left"><p>2222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222</p> </div> <div class="right"> 11111111111111111111111111111111 11111111111111111111111111111111 11111111111111111111111111111111 11111111111111111111111111111111 </div> </div> 123 </body> </html>
第三種:左邊和右邊都用相對定位spa
<!doctype html> <html> <head> <meta charset="utf-8"> <title>左側定寬,右側自適應(3)</title> <style type="text/css"> *{margin: 0;padding: 0;} div.contain{background: yellow; position: relative; height: 400px;} div.left{ position: absolute; left: 0;top: 0; width: 200px;height: 400px;background: red; word-break: break-all;} div.right{position: absolute; left: 200px;top: 0; height: 400px; background: blue; word-break: break-all;} </style> </head> <body> <div class="contain"> <div class="left"><p>2222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222</p> </div> <div class="right"> 11111111111111111111111111111111 11111111111111111111111111111111 11111111111111111111111111111111 11111111111111111111111111111111 </div> </div> 123 </body> </html>
最後,若是有更好更多的方法,願您能告訴我一聲。。。code