百度面试笔试中有一题是写一个三栏布局,两边固定300px,中间自适应。以为自己写对了,回来后上网才知道原来错了撒。
我的答案:
1 <div class="left">1</div> 2 <div class="center">2</div> 3 <div class="right">3</div> 4 <style text="type/css"> 5 div{display:inline-block;} 6 .left, .right{ width:300px; background:red;} 7 .center{ width:auto;} 8 </style>
网上答案
http://www.w3cplus.com/css/layout-column-three
主要有定位,浮动和通过margin来控制布局三种方法。同时还给出了一个三栏布局,中间固定,两边自适应的例子。
定位:
1 <div id="left">左边栏</div> 2 <div id="right">右边栏</div> 3 <div id="main">主内容</div> 4 html,body { 5 margin:0; 6 padding:0; 7 height: 100%; 8 } 9 10 #left, 11 #right { 12 position: absolute; 13 top:0; 14 220px; 15 height: 100%; 16 } 17 18 #left { 19 left:0; 20 } 21 22 #right { 23 right:0; 24 } 25 26 #main { 27 margin: 0 230px; 28 height: 100%; 29 }
浮动:
<div id="left">left </div> <div id="right">right</div> <div id="main">mian</div> #left, #right { float: left; 220px; height: 200px; background: blue; } #right{ float: right; } #main { margin: 0 230px; background: red; height: 200px; }
负边距:
1 <div id="main"> 2 <div id="mainContainer">main content</div> 3 </div> 4 <div id="left"> 5 <div id="leftContainer" class="inner">left content</div> 6 </div> 7 <div id="right"> 8 <div id="rightContainer" class="inner">right</div> 9 </div> 10 #main { 11 float: left; 12 100%; 13 } 14 #mainContainer { 15 margin: 0 230px; 16 height: 200px; 17 background: green; 18 } 19 #left { 20 float: left; 21 margin-left: -100%; 22 230px 23 } 24 25 #right { 26 float: left; 27 margin-left: -230px; 28 230px; 29 } 30 31 #left .inner, 32 #right .inner { 33 background: orange; 34 margin: 0 10px; 35 height: 200px; 36 }
中间固定,两边自适应:
1 <div id="left"> 2 <div class="inner">this is left sidebar content</div> 3 </div> 4 <div id="main"> 5 <div class="inner">this is main content</div> 6 </div> 7 <div id="right"> 8 <div class="inner">this is right siderbar content</div> 9 </div> 10 #left, 11 #right { 12 float: left; 13 margin: 0 0 0 -271px; 14 50%; 15 } 16 17 #main { 18 540px; 19 float: left; 20 background: green; 21 } 22 23 .inner { 24 padding: 20px; 25 } 26 27 #left .inner, 28 #right .inner { 29 margin: 0 0 0 271px; 30 background: orange; 31 }
这种方法如果在ie下会存在布局混乱的bug,你可以将div#right和div#left中的width值稍作修改:
1 #left, 2 #right { 3 float: left; 4 margin: 0 0 0 -271px; 5 50%; 6 * 49.9%; 7 }
CSS3 Flexbox
1 <div class="grid"> 2 <div class="col fluid"> 3 ... 4 </div> 5 <div class="col fixed"> 6 ... 7 </div> 8 <div class="col fluid"> 9 ... 10 </div> 11 </div> 12 .grid { 13 display: -webkit-flex; 14 display: -moz-flex; 15 display: -o-flex; 16 display: -ms-flex; 17 display: flex; 18 } 19 .col { 20 padding: 30px; 21 } 22 .fluid { 23 flex: 1; 24 } 25 .fixed { 26 400px; 27 }
有关flexbox的内容:
http://www.w3.org/html/ig/zh/wiki/Css3-flexbox/zh-hans