Pseudo-element :before (หรือ ::before)
ใช้ ::before (รูปแบบใหม่) หรือ :before (รูปแบบเก่า) เพื่อแทรกเนื้อหา ก่อน เนื้อหาขององค์ประกอบ
ไวยากรณ์
selector::before {
content: "ข้อความหรือค่า";
/* สไตล์อื่นๆ */
}
ตัวอย่าง: เพิ่ม bullet ก่อนแต่ละย่อหน้า
<html>
<head>
<style>
p::before {
content: url(/images/bullet.gif);
margin-right: 8px;
}
</style>
</head>
<body>
<p>บรรทัดนี้จะมี bullet นำหน้า</p>
<p>บรรทัดนี้จะมี bullet นำหน้า</p>
<p>บรรทัดนี้จะมี bullet นำหน้า</p>
</body>
</html>
ค่า content ที่ใช้ได้ (เหมือน ::after)
| ประเภท | ตัวอย่าง |
|---|---|
| ข้อความ | content: "▶ "; |
| Attribute | content: attr(data-label); |
| Counter | content: counter(section) ". "; |
| รูปภาพ | content: url(icon.svg); |
| Empty (สร้าง shape) | content: ""; |
การใช้งานจริงยอดนิยม
1. Automatic Numbering (ลำดับอัตโนมัติ)
body { counter-reset: section; }
h2::before {
counter-increment: section;
content: "Section " counter(section) ": ";
font-weight: bold;
color: #666;
}
2. Icon Prefix
.external-link::before {
content: url(external-icon.svg);
margin-right: 4px;
vertical-align: middle;
}
.pdf-link::before {
content: "📄 ";
}
3. Decorative Elements
.quote::before {
content: "";
display: block;
width: 4px;
height: 100%;
background: linear-gradient(to bottom, #ff6b6b, #4ecdc4);
position: absolute;
left: -16px;
}
4. Form Validation Indicators
.required::before {
content: "* ";
color: red;
}
.invalid::before {
content: "✗ ";
color: red;
}
.valid::before {
content: "✓ ";
color: green;
}
5. Clearfix (เหมือน ::after)
.clearfix::before,
.clearfix::after {
content: "";
display: table;
}
.clearfix::after { clear: both; }
⚠️ ข้อจำกัด (เหมือน ::after)
- ไม่ได้อยู่ใน DOM - ไม่ select/copy ได้, JS เข้าถึงไม่ได้
- Screen readers อาจอ่าน/ไม่อ่าน
- ไม่ใช้กับ replaced elements (img, input, br, hr, video, iframe)
- ต้องมี
contentproperty เสมอ (แม้แค่"")