การจัดตำแหน่งโดย CSS ด้วย float และ clear
หน้าแรก CSS การจัดตำแหน่งโดย CSS ด้วย float และ clear
float และ clear เป็น property ที่สำคัญอันหนี่ง ที่มีไว้เพื่อการจัดตำแหน่งของ layout ในแบบ tableless property ทั้งสองตัวมีความหมายดังนี้ครับ
float: left มีความหมายเหมือนกับ align=left แหละครับ คือจัดให้ชิดซ้าย
float: right มีความหมายเหมือนกับ alight=right ครับ คือจัดให้ชิดขวา
clear: left หมายถึง ไม่ให้มีอะไรอยู่ข้างซ้ายของมัน
clear: right หมายถึง ไม่ให้มีอะไรอยู่ด้านขวาของมัน
clear: both หมายถึง ไม่ให้ทีอะไรอยู่ทั้ง 2 ด้านของมันเลย
| Code |
| <style type="text/css"> .clear{clear:both; line-height:0; height:0; font-size: 1px} .box-1{width:100px; height:100px; background:#FFCC00; float:left} .box-2{width:100px; height:100px; background:#99CC00; float:right;} #frame{width:300px ;background:#AAAAAA} </style> <div id="frame"> <div class="box-1">float:left</div> <div class="box-2">float:right</div> <br class="clear" /> </div> |
ถ้าสังเกตุให้ดีจะเห็นอะไรแปลกๆอยู่อย่างหนึ่ง คือ <br class="clear" /> มันมีไว้ทำอะไรหว่า...(อยากรู้ก็ลองถอดออกดูสิครับ)
โค้ดด้านบน หากไม่มี <br class="clear" /> มันจะแสดงผลได้ถูกต้องบน IE ครับ แต่ถ้าเป็น Firefox พื้นหลัง(สีเทา) มันจะไม่ขยายตามความสูงของ box ทำให้เราต้อง hack มันด้วยการเติม <br class="clear" /> ลงไปในโค้ดเพื่อให้มันแสดงผลได้เหมือนๆกันในทุกบราวเซอร์
ในทางปฏิบัติเราอาจใช้ br หรือ div ก็ได้ครับ โดยใช้ร่วมกับ class clear
| Code |
| .clear{clear:both; line-height:0; height:0; font-size: 1px} |
แต่ไม่แนะนำ p หรือ span เนื่องจาก p และ span เป็น text node ถ้าไม่มีข้อความภายในอาจไม่ผ่านการ validate w3c ครับ
ลองมาดูตัวอย่างการทำ layout ดูครับ
| Code |
| <style type="text/css"> .clear{clear:both; line-height:0; height:0; font-size: 1px} #menu{float: left; width: 100px; height: 200px; background: olive} #content{float: right; width: 200px} .box-1{width:90px; height:100px; background:#FFCC00; float:left} .box-2{width:90px; height:100px; background:#99CC00; float:right;} #header{background: #999999} #footer{background: #666666} #frame{background: red} #header,#frame,#footer{clear: both; margin: 0 auto; width: 300px; text-align: center} </style> <div id="header">clear:both</div> <div id="frame"> <div id="menu">float:left</div> <div id="content"> <div class="box-1">float:left</div> <div class="box-2">float: right</div> float: right </div> <div class="clear"></div> </div> <div id="footer">clear:both</div> |
refer: http://www.goragod.com/knowledge/%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%88%E0%B8%B1%E0%B8%94%E0%B8%95%E0%B8%B3%E0%B9%81%E0%B8%AB%E0%B8%99%E0%B9%88%E0%B8%87%E0%B9%82%E0%B8%94%E0%B8%A2%20CSS%20%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2%20float%20%E0%B9%81%E0%B8%A5%E0%B8%B0%20clear.html
ขึ้นไปด้านบน
