เราสามารถจัดรูปแบบเฉพาะบางส่วนขององค์ประกอบ เช่น อักษรตัวแรก บรรทัดแรก หรือแม้แต่แทรกก่อน/หลัง เพื่อจุดประสงค์เหล่านี้ใช้องค์ประกอบหลอก CSS
หมายเหตุ − ในการแยก CSS Pseudo Classes ออกจาก Pseudo Elements ใน CSS3 องค์ประกอบหลอกใช้สัญกรณ์เครื่องหมายทวิภาค
ไวยากรณ์
ต่อไปนี้เป็นรูปแบบการใช้ CSS Pseudo องค์ประกอบ -
Selector::pseudo-element {
css-property: /*value*/;
} ต่อไปนี้เป็น CSS Pseudo Elements ทั้งหมด -
| ซีเนียร์ | องค์ประกอบหลอก &คำอธิบาย |
|---|---|
| 1 | หลัง มันแทรกบางอย่างหลังจากเนื้อหาของแต่ละองค์ประกอบที่กล่าวถึง |
| 2 | ก่อน มันแทรกบางอย่างก่อนเนื้อหาของแต่ละองค์ประกอบที่กล่าวถึง |
| 3 | อักษรตัวแรก จะเลือกอักษรตัวแรกของแต่ละองค์ประกอบที่กล่าวถึง |
| 4 | บรรทัดแรก จะเลือกบรรทัดแรกของแต่ละองค์ประกอบที่กล่าวถึง |
| 5 | ตัวยึดตำแหน่ง จะเลือกข้อความตัวแทนในองค์ประกอบของฟอร์ม |
| 6 | การเลือก มันเลือกส่วนขององค์ประกอบที่ผู้ใช้เลือก |
มาดูตัวอย่าง CSS Pseudo Elements กัน −
ตัวอย่าง
<!DOCTYPE html>
<html>
<head>
<style>
p::first-letter {
background-color: black;
}
p::first-line {
background-color: lightgreen;
color: white;
}
span {
font-size: 2em;
color: #DC3545;
}
</style>
</head>
<body>
<h2>Computer Networks</h2>
<p><span>A</span> system of interconnected computers and computerized peripherals such as printers is called computer network. </p>
</body>
</html> ผลลัพธ์
มาดูตัวอย่างอื่นของ CSS Pseudo Elements กัน −

ตัวอย่าง
<!DOCTYPE html>
<html>
<head>
<style>
div:nth-of-type(1) p:nth-child(2)::after {
content: " LEGEND!";
background: orange;
padding: 5px;
}
div:nth-of-type(2) p:nth-child(2)::before {
content: "Book:";
background-color: lightblue;
font-weight: bold;
padding: 5px;
}
</style>
</head>
<body>
<div>
<p>Cricketer</p>
<p>Sachin Tendulkar:</p>
</div>
<hr>
<div>
<p><q>Chase your Dreams</q></p>
<p><q>Playing It My Way</q></p>
</div>
</body>
</html> ผลลัพธ์
