คุณสมบัติ display ใน CSS ใช้ควบคุมการแสดงผลและลักษณะการวางของ element บนหน้าเว็บ
ค่าหลักของ Display Property
| ลำดับ | ค่า | คำอธิบาย |
|---|---|---|
| 1 | inline | แสดงเป็น inline element (ไม่ขึ้นบรรทัดใหม่, ไม่กำหนด width/height ได้) |
| 2 | block | แสดงเป็น block element (ขึ้นบรรทัดใหม่, กำหนด width/height ได้) |
| 3 | contents | ทำให้ container หายไป ลูก elements กลายเป็นลูกของ parent ระดับบน |
| 4 | flex | แสดงเป็น block-level flex container |
| 5 | grid | แสดงเป็น block-level grid container |
| 6 | inline-block | แสดงเป็น inline-level block container (inline แต่กำหนด width/height ได้) |
| 7 | inline-flex | แสดงเป็น inline-level flex container |
| 8 | inline-grid | แสดงเป็น inline-level grid container |
| 9 | inline-table | แสดงเป็น inline-level table |
| 10 | none | ซ่อน element ทั้งหมด (ไม่ครองพื้นที่ ไม่เข้าถึงได้) |
| 11 | table, table-row, table-cell, ฯลฯ | ทำให้ element พฤติกรรมเหมือนตาราง |
| 12 | list-item | แสดงเหมือน <li> พร้อม marker |
| 13 | run-in | พฤติกรรมผสม inline/block ตาม context |
ตัวอย่างที่ 1: none และ inline
<!DOCTYPE html> <html> <head> <style> span { background-color: orange; color: white; } p.demo { display: none; } span.demo1 { display: inline; } </style> </head> <body> <h1>Match Details</h1> <div> Match will begin at <p class="demo">9AM</p> 10AM on 20th December. </div> <div> Match will end at <span class="demo1">5PM</span> on 20th December. </div> </body> </html>
ตัวอย่างที่ 2: block และ inline-block
<!DOCTYPE html> <html> <head> <style> p { background-color: orange; color: white; } p.demo1 { display: block; } p.demo2 { display: inline-block; } </style> </head> <body> <h1>Match Details</h1> <div> Match will begin at <p class="demo1">10AM</p> on 19th Decemenber, 2019. </div> <div> Match will end at <p class="demo2">5PM</p> on 19th Decemenber, 2019. </div> </body> </html>
คำอธิบาย
ตัวอย่างที่ 1: p.demo ถูกซ่อนด้วย display: none (ไม่แสดง 9AM) ส่วน span.demo1 แสดงแบบ inline ต่อเนื่องกับข้อความ
ตัวอย่างที่ 2: p.demo1 เป็น block (ขึ้นบรรทัดใหม่) ส่วน p.demo2 เป็น inline-block (อยู่บรรทัดเดียวกัน แต่กำหนด width/height ได้)
display: none vs visibility: hidden
| คุณสมบัติ | display: none | visibility: hidden |
|---|---|---|
| ครองพื้นที่ | ไม่ | ใช่ |
| เข้าถึงได้ (accessibility) | ไม่ (screen reader ข้าม) | ไม่ (แต่ครองพื้นที่) |
| events | ไม่รับ event | ไม่รับ event |
| transition/animation | ไม่ทำงาน | ทำงานได้ |