【css面試題】三個DIV要求水平對齊,左右兩個DIV寬度固定為100px,中間那個DIV充滿剩餘的寬度(至少2種方法),div100px
這是我在一家公司面試時遇到的問題,當時沒有答上來!!
所以看到的小夥伴一定要注意了!!
變化瀏覽器寬度可看到效果:
左右中
然後我們來看看代碼:
第一種方法:(浮動)
<style type="text/css"> .left,.right,.center{ border:1px solid; height:100px; text-align: center; line-height:100px; font-size:50px; } .left{ float:left; width:100px; } .right{ float:right; width:100px; } .center{ margin:0 100px; }</style><div> <div class="left">左</div> <div class="right">右</div> <div class="center">中</div></div>
第二種方法:(絕對位置)
<style type="text/css"> .container{ position: relative; } .left,.right,.center{ position:absolute;/*增加絕對位置*/ top:0; border:1px solid; height:100px; text-align: center; line-height:100px; font-size:50px; } .left{ left:0; width:100px; } .right{ right:0; width:100px; } .center{ width:auto; left:100px; right:100px; }</style><div class="container"> <div class="left">左</div> <div class="right">右</div> <div class="center">中</div></div>
剛發布不久,就有個小夥伴在下面評論了第三種方法
第三種方法:(fiex)
瀏覽器支援
目前主流瀏覽器不支援 box-flex 屬性。
Internet Explorer 10 通過私人屬性 the -ms-flex 支援.
Firefox通過私人屬性 -moz-box-flex 支援.
Safari和Chrome通過私人屬性 -webkit-box-flex 支援.
注意: Internet Explorer 9及更早IE版本不支援彈性方塊.
<style type="text/css"> .container{ display:-moz-box; /* Firefox */ display:-webkit-box; /* Safari and Chrome */ display:box; } .left,.right,.center{ border:1px solid; height:100px; text-align: center; line-height:100px; font-size:50px; } .left{ width:100px; } .right{ width:100px; } .center{ -moz-box-flex:1.0; /* Firefox */ -webkit-box-flex:1.0; /* Safari 和 Chrome */ box-flex:1.0; }</style><div class="container"> <div class="left">左</div> <div class="center">中</div> <div class="right">右</div></div>
當然還有很多方法,如果你有什麼更好的方法,希望你能在下面評論出來,我們大家一起學習