Property style.clear ควบคุมพฤติกรรมของ Element เทียบกับ Floating Elements (float: left/right) ไม่ได้ "ดึงตำแหน่ง" แต่ "กำหนดกฎการวาง"
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<style>
img { float: left; }
</style>
</head>
<body>
<img src="https://www.tutorialspoint.com/videotutorials/images/tutor_connect_home.jpg" width="170" height="150">
<p id="myP">Demo content! ... (long text)</p>
<button type="button" onclick="display()">Click</button>
<script>
function display() {
document.getElementById("myP").style.clear = "left";
}
</script>
</body>
</html>
ค่าของ clear Property
| ค่า | ความหมาย |
|---|---|
none | Default: ขึ้นติด Floating Element ได้ (ถ้าพอ) |
left | เลื่อนลงจนกว่าจะไม่มี Float ด้านซ้าย |
right | เลื่อนลงจนกว่าจะไม่มี Float ด้านขวา |
both | เลื่อนลงจนกว่าจะไม่มี Float ทั้งสองด้าน |
inline-start/end | Logical Properties (RTL/LTR Aware) |
การทำงานในตัวอย่าง
- รูปภาพ
float: leftอยู่ซ้าย <p>ขึ้นติดข้างขวารูป (Wrap Around)- กดปุ่ม →
clear: left→<p>โดนผลักลงมาใต้รูปภาพ
Clearfix Pattern (สมัยใหม่)
/* แทนที่จะใช้ clear บน Element ถัดไป ให้ Clear บน Container */
.container::after {
content: "";
display: table;
clear: both;
}
/* หรือ Modern */
.container {
display: flow-root; /* สร้าง BFC เอง */
}
แก้ไขข้อมูลต้นฉบับ: คำอธิบายเดิม "return the position of the element relative to floating objects" ผิด — clear ไม่ได้ Return Position แต่ Control Layout Behavior