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

วิธีจัดสไตล์ HTML ด้วยแท็ก span (Inline Styling)

แท็ก <span> เป็น inline container ใช้จัดกลุ่มและ apply style ให้ส่วนหนึ่งของข้อความ (inline-level) ไม่สร้างบรรทัดใหม่

ความแตกต่าง span vs div

spandiv
Inline elementBlock element
ไม่ขึ้นบรรทัดใหม่ขึ้นบรรทัดใหม่
วางใน block element ได้ไม่ควรวางใน inline element
ใช้สำหรับ text fragmentใช้สำหรับ section layout

ตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <title>HTML span Tag</title>
</head>
<body>
  <p>Java is a Programming language widely followed. 
    <span style="color:#FF0000;">Developed by James Gosling.</span>
    This is demo text.</p>
  <p>
    <span style="color:#8866ff;">Current Version: 1.8</span>
  </p>
</body>
</html>

ผลลัพธ์

Java is a Programming language widely followed. Developed by James Gosling. This is demo text.

Current Version: 1.8

การใช้งานจริง (Best Practice)

.highlight { background: #fff3cd; padding: 0.2em 0.4em; border-radius: 3px; }
.keyword { font-weight: bold; color: #d63384; }
.version { font-family: monospace; color: #6f42c1; }
<p>Learn <span class="keyword">JavaScript</span> version <span class="version">ES2024</span></p>

Accessibility

  • <span> ไม่มี semantic meaning ใช้เฉพาะ styling
  • หากมีความหมาย (emphasis, code, keyboard input) ใช้ <em>, <strong>, <code>, <kbd> แทน
  • ใช้ aria-label หากจำเป็น