คุณสมบัติ HTML DOM Style flex ใช้สำหรับตั้งค่าหรือส่งคืนความยาวแบบยืดหยุ่นสำหรับองค์ประกอบที่มีคุณสมบัติ display ตั้งเป็น flex ใช้จัดการคุณสมบัติ flexGrow, flexShrink และ flexBasis พร้อมกัน
ไวยากรณ์ (Syntax)
การตั้งค่าคุณสมบัติ flex:
object.style.flex = "flex-grow flex-shrink flex-basis|auto|initial|inherit"
ค่าของคุณสมบัติ (Property Values)
| ค่า | คำอธิบาย |
|---|---|
| flex-grow | ขยาย item เทียบกับ flex items อื่นๆ ตามตัวเลขที่กำหนด |
| flex-shrink | หดตัว item เทียบกับ flex items อื่นๆ ตามตัวเลขที่กำหนด |
| flex-basis | ระบุความยาวของ item รับหน่วยความยาวที่ถูกต้องทั้งหมด |
| auto | ตั้งค่าคุณสมบัติ flex ทั้งสามเป็น 1 1 auto |
| initial | ตั้งค่าคุณสมบัติ flex เป็นค่าเริ่มต้นคือ 0 1 auto |
| none | เทียบเท่า 0 0 auto |
| inherit | สืบทอดค่าคุณสมบัติจากองค์ประกอบพาเรนต์ |
ตัวอย่างการใช้งาน
<!DOCTYPE html> <html> <head> <style>
#demo {
width: 400px;
height: 80px;
display: flex;
}
#demo div {
flex: 1 3 auto;
}
div:nth-of-type(even) {
box-shadow: inset 0 0 12px red;
}
div:nth-of-type(odd) {
box-shadow: inset 0 0 12px blue;
}
</style> <script>
function changeFlex() {
document.getElementsByTagName("DIV")[1].style.flex = "none";
document.getElementsByTagName("DIV")[4].style.flex = "none";
document.getElementById("Sample").innerHTML = "ค่า flex ของ div ที่ 1 และ 4 ถูกเปลี่ยนเป็น none";
}
</script> </head> <body>
<div id="demo">
<div id="orange"></div>
<div id="green"></div>
<div id="blue"></div>
<div id="red"></div>
</div>
<p>คลิกปุ่มด้านล่างเพื่อเปลี่ยนคุณสมบัติ flex ของ div ด้านบน</p>
<button onclick="changeFlex()">เปลี่ยน Flex</button>
<p id="Sample"></p>
</body> </html>
ผลลัพธ์

เมื่อคลิกปุ่ม "เปลี่ยน Flex":
