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

CSS :before pseudo-element: เพิ่มเนื้อหาก่อนองค์ประกอบ


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: "▶ ";
Attributecontent: attr(data-label);
Countercontent: 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)
  • ต้องมี content property เสมอ (แม้แค่ "")