แท็ก <span> เป็น inline container ใช้จัดกลุ่มและ apply style ให้ส่วนหนึ่งของข้อความ (inline-level) ไม่สร้างบรรทัดใหม่
ความแตกต่าง span vs div
| span | div |
|---|---|
| Inline element | Block 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หากจำเป็น