Pseudo-element :after (หรือ ::after)
ใช้ ::after (รูปแบบใหม่) หรือ :after (รูปแบบเก่า) เพื่อแทรกเนื้อหา หลัง เนื้อหาขององค์ประกอบ โดยไม่ต้องเพิ่ม HTML
ไวยากรณ์
selector::after {
content: "ข้อความหรือค่า";
/* สไตล์อื่นๆ */
}
ตัวอย่าง: เพิ่มไอคอน/สัญลักษณ์
<html>
<head>
<style>
p::after {
content: url(/images/bullet.gif);
margin-left: 8px;
}
</style>
</head>
<body>
<p>บรรทัดนี้จะมี bullet ต่อท้าย</p>
<p>บรรทัดนี้จะมี bullet ต่อท้าย</p>
<p>บรรทัดนี้จะมี bullet ต่อท้าย</p>
</body>
</html>
ค่า content ที่ใช้ได้
| ประเภท | ตัวอย่าง |
|---|---|
| ข้อความ | content: " ★"; |
| Attribute | content: attr(href); / attr(data-tooltip) |
| Counter | content: counter(item); |
| รูปภาพ | content: url(icon.svg); |
| Gradient | content: ""; background: linear-gradient(...); |
| Empty | content: ""; (ใช้สร้าง shape/decorative) |
การใช้งานจริงยอดนิยม
1. Clearfix (ล้าง float)
.clearfix::after {
content: "";
display: table;
clear: both;
}
2. Tooltip
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
background: #333;
color: white;
padding: 4px 8px;
border-radius: 4px;
white-space: nowrap;
opacity: 0;
pointer-events: none;
transition: opacity 0.2s;
}
.tooltip:hover::after { opacity: 1; }
3. Quote Marks
blockquote::before { content: open-quote; }
blockquote::after { content: close-quote; }
4. Decorative Shapes
.card::after {
content: "";
position: absolute;
top: 0; right: 0;
width: 20px; height: 20px;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
border-radius: 0 0 0 10px;
}
⚠️ ข้อจำกัด
- ไม่สามารถเลือก (select) หรือ copy เนื้อหาได้
- ไม่เข้าถึงได้จาก JavaScript (ไม่ได้อยู่ใน DOM)
- Screen readers อาจอ่านหรือไม่อ่าน ขึ้นอยู่กับการตั้งค่า
- ไม่ใช้กับ
img,input,br,hr(replaced elements)