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

Pseudo-element ใน CSS คืออะไร

CSS Pseudo-element คือตัวเลือก (selector) สำหรับส่วนเฉพาะขององค์ประกอบ เช่น ตัวอักษรแรก (::first-letter), บรรทัดแรก (::first-line) และ ::before, ::after สำหรับแทรกเนื้อหาก่อน/หลังองค์ประกอบ

ไวยากรณ์ (Syntax)

Selector::pseudo-element {
  css-property: /*value*/;
}

ตัวอย่างที่ 1: ใช้ ::before และ ::after กับ counter

<!DOCTYPE html>
<html>
<head>
  <style>
    ol, ul { list-style: none; counter-reset: demo_var2; }
    ul { counter-reset: demo_var1; }
    ol > li::before {
      counter-increment: demo_var2;
      content: counter(demo_var2, lower-roman) ") ";
    }
    li::after {
      counter-increment: demo_var1;
      content: " " counter(demo_var1) ". ";
    }
  </style>
</head>
<body>
  <ul>
    <li>Demo Line</li>
    <ol>
      <li>demo line</li>
      <li>demo line</li>
    </ol>
    <li>Demo Line</li>
    <ol>
      <li>demo line</li>
      <li>demo line</li>
    </ol>
    <li>Demo Line</li>
  </ul>
</body>
</html>

ผลลัพธ์

Pseudo-element ใน CSS คืออะไร

ตัวอย่างที่ 2: จัดสไตล์ Placeholder ด้วย ::placeholder

<!DOCTYPE html>
<html>
<head>
  <style>
    ::-webkit-input-placeholder { /* Edge */
      color: blue; font-style: italic;
    }
    :-ms-input-placeholder { /* IE */
      color: blue; font-style: italic;
    }
    ::placeholder { /* Standard */
      color: blue; font-style: italic;
    }
  </style>
</head>
<body>
  <h2> Sample Form </h2>
  <textarea id="desc" name="desc" rows="5" cols="33" placeholder="Type here"></textarea>
  <br />
  <input type="text" name="author" placeholder="author name">
</body>
</html>

ผลลัพธ์

Pseudo-element ใน CSS คืออะไร

Pseudo-elements ที่พบบ่อย

Pseudo-elementคำอธิบาย
::beforeแทรกเนื้อหาก่อนองค์ประกอบ
::afterแทรกเนื้อหาหลังองค์ประกอบ
::first-letterตัวอักษรแรกของเนื้อหา
::first-lineบรรทัดแรกของเนื้อหา
::selectionส่วนที่ผู้ใช้ไฮไลท์
::placeholderข้อความ placeholder ใน input/textarea
::markerเครื่องหมาย bullet/number ของ list item

หมายเหตุ: ใช้เครื่องหมาย :: สองจุด (CSS3) แทน : จุดเดียว (CSS2) เพื่อแยกจาก pseudo-class