Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

การซ่อน Element ด้วย CSS display: none

ใช้ display: none เพื่อซ่อน element อย่างสมบูรณ์ - ไม่แสดง ไม่ครองพื้นที่ และไม่เข้าถึงได้

ตัวอย่างที่ 1: ซ่อน paragraph

<!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: ซ่อน span ภายใน paragraph

<!DOCTYPE html> <html> <head> <style> span {    display: none; } .demo2 {    text-decoration: underline;    text-decoration-style: double;    text-decoration-color: red; } </style> </head> <body> <h1>Details</h1> <p class="demo">Examination Center near <span>XYZ College</span> ABC College.</p> <p class="demo2">Exam begins at 11AM.</p> </body> </html>

คำอธิบาย

ตัวอย่างที่ 1: <p class="demo">9AM</p> ถูกซ่อน ทำให้ข้อความต่อเนื่องเป็น "10AM on 20th December"

ตัวอย่างที่ 2: <span>XYZ College</span> ถูกซ่อน ทำให้เหลือ "Examination Center near ABC College."

เมื่อไหร่ควรใช้ display: none

  • ซ่อนเนื้อหาที่ไม่ต้องการแสดงเลย (mobile vs desktop)
  • Toggle เนื้อหาด้วย JavaScript (show/hide)
  • Skip links สำหรับ accessibility
  • Print stylesheet (ซ่อน nav, ads)

เมื่อไหร่ไม่ควรใช้

  • ต้องการ animation fade in/out → ใช้ opacity + visibility
  • ต้องการ screen reader อ่านได้ → ใช้ visually-hidden pattern
  • ต้องการครองพื้นที่ไว้ → ใช้ visibility: hidden

Visually Hidden Pattern (สำหรับ accessibility):

.visually-hidden {
  position: absolute;
  width: 1px; height: 1px;
  padding: 0; margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}