การจัดตำแหน่งโดย CSS ด้วย float และ clear

float และ clear เป็น property ที่สำคัญอันหนี่ง ที่มีไว้เพื่อการจัดตำแหน่งของ layout ในแบบ tableless property ทั้งสองตัวมีความหมายดังนี้ครับ

float: left มีความหมายเหมือนกับ align=left แหละครับ คือจัดให้ชิดซ้าย
float: right มีความหมายเหมือนกับ alight=right ครับ คือจัดให้ชิดขวา
clear: left หมายถึง ไม่ให้มีอะไรอยู่ข้างซ้ายของมัน
clear: right หมายถึง ไม่ให้มีอะไรอยู่ด้านขวาของมัน
clear: both หมายถึง ไม่ให้ทีอะไรอยู่ทั้ง 2 ด้านของมันเลย
<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;text-align: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>

โค้ด CSS ด้านบนจะให้ผลลัพท์เหมือนด้านล่างนี่แหละครับ
float:left
float:right

ถ้าสังเกตุให้ดีจะเห็นอะไรแปลกๆอยู่อย่างหนึ่ง คือ <br class="clear" /> มันมีไว้ทำอะไรหว่า...(อยากรู้ก็ลองถอดออกดูสิครับ)

โค้ดด้านบน หากไม่มี <br class="clear" /> มันจะแสดงผลได้ถูกต้องบน IE ครับ แต่ถ้าเป็น Firefox พื้นหลัง(สีเทา) มันจะไม่ขยายตามความสูงของ box ทำให้เราต้อง hack มันด้วยการเติม <br class="clear" /> ลงไปในโค้ดเพื่อให้มันแสดงผลได้เหมือนๆกันในทุกบราวเซอร์

ในทางปฏิบัติเราอาจใช้ br หรือ div ก็ได้ครับ โดยใช้ร่วมกับ class clear
.clear{clear:both; line-height:0; height:0; font-size: 1px}

แต่ไม่แนะนำ p หรือ span เนื่องจาก p และ span เป็น text node ถ้าไม่มีข้อความภายในอาจไม่ผ่านการ validate w3c ครับ

ลองมาดูตัวอย่างการทำ layout ดูครับ
<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>

โค้ดด้านบน จะให้ผลลัพท์ดังด้านล่างนี้ครับ
clear:both
float:left
float:left
float: right
float: right
ผู้เขียน goragod โพสต์เมื่อ 19 ส.ค. 2553 เปิดดู 95,847 ป้ายกำกับ XHTMLCSS
^