網頁上免不了要用到的區塊併排,常用的方式有float和inline-block這種方式,這一篇介紹float的設定方法和相關應用。
下面是要製作併排時基本會用到的html和css,可以複製以下的語法來練習
html部份:
1 2 3 4 5 6 7 8 9 10 11 |
<div id="outside"> <div class="box"> class "box" 的內容放在這裡1</div> <div class="box"> class "box" 的內容放在這裡2</div> <div class="box"> class "box" 的內容放在這裡3</div> <div class="box"> class "box" 的內容放在這裡4</div> <div class="box"> class "box" 的內容放在這裡5</div> <div class="box"> class "box" 的內容放在這裡6</div> <div class="box"> class "box" 的內容放在這裡7</div> <div class="box"> class "box" 的內容放在這裡8</div> <div id="bottom"> id "bottom" 的內容放在這裡</div> </div> |
css部份:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#outside { background-color: #FF0; width: 580px; margin: 5px; padding: 10px; } .box { margin: 5px; float: left; height: 70px; width: 70px; background-color: #F90; padding: 10px; border: 5px solid #900; } |
要重覆出現並且併排的.box物件上套用float:left則物件會由左至右排列,反之套用float:right則物件會由右至左排列。
當外框物件有設定"寬width"時,.box物件會依外框寬度自動換行。
背景色延伸
如上圖所呈現的,內容物件套用float屬性之後背景色不會跟著內容的長度而延伸,如果希望背景可以延伸的話,在外框再加入overflow:auto的屬性就可以
1 2 3 4 5 6 7 |
#outside { background-color: #FF0; width: 580px; overflow: auto; margin: 5px; padding: 10px; } |
底部區塊不併排
當我們在.box物件的最後加入一個#bottom物件,這個最底下的物件會因為上面.box物件的float屬性而被壓在後面。
1 2 3 4 |
#bottom { background-color: #6CF; height: 50px; } |
如果希望這個#bottom物件可以跟外框一樣寬,不併排的話,需要在#bottom上套用"clear:both; 清除浮動"的屬性。
※如果連結float屬性區塊的最後,有一個帶有clear:both;屬性的區塊的話,那外框就不用再加overflow:auto了。
1 2 3 4 5 |
#bottom { background-color: #6CF; height: 50px; clear: both; } |
用圖片說明的話大概是下面這樣:
最後附上完整的css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#outside { background-color: #FF0; width: 580px; overflow: auto; margin: 5px; padding: 10px; } .box { margin: 5px; float: left; height: 70px; width: 70px; background-color: #F90; padding: 10px; border: 5px solid #900; } #bottom { background-color: #6CF; height: 50px; clear: both; } |