คุณสมบัติ position ของ Style ใน HTML DOM ใช้สำหรับอ่านหรือตั้งค่าวิธีการจัดตำแหน่ง (positioning method) ของเอลิเมนต์ HTML ในเอกสาร HTML
รูปแบบการใช้งาน (Syntax)
1. อ่านค่า position
object.position
2. ตั้งค่า position
object.position = "value"
ค่าที่เป็นไปได้ (Value) มีดังนี้:
| ลำดับ | ค่าและคำอธิบาย |
|---|---|
| 1 | initial ตั้งค่าคุณสมบัติเป็นค่าเริ่มต้น |
| 2 | inherit สืบทอดค่าจากเอลิเมนต์พาเรนต์ |
| 3 | static เอลิเมนต์จะแสดงตามลำดับใน document flow (ค่าเริ่มต้น) |
| 4 | absolute จัดตำแหน่งสัมพัทธ์กับ ancestor element ที่มี position อยู่ก่อนหน้าสุด |
| 5 | fixed จัดตำแหน่งสัมพัทธ์กับหน้าต่างเบราว์เซอร์ (viewport) |
| 6 | relative จัดตำแหน่งสัมพัทธ์กับตำแหน่งปกติของตัวมันเอง |
| 7 | sticky จัดตำแหน่งตามตำแหน่งการเลื่อน (scroll) ของผู้ใช้ |
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
height: 100vh;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 2px;
width: 40%;
display: block;
color: #fff;
outline: none;
cursor: pointer;
margin: 1rem 0;
}
.square {
width: 100px;
height: 100px;
background: #db133a6b;
top: 150px;
left: 50%;
}
.show {
font-size: 1.2rem;
margin: 1rem 0;
}
</style>
<body>
<h1>ตัวอย่างคุณสมบัติ position ของ Style</h1>
<div class='square'></div>
<button onclick="set()" class="btn">ตั้งค่า Position</button>
<script>
function set() {
document.querySelector('.square').style.position = "fixed";
}
</script>
</body>
</html>
ผลลัพธ์
คลิกที่ปุ่ม "ตั้งค่า Position" เพื่อตั้งค่าตำแหน่งของ สี่เหลี่ยมสีชมพู

