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

บทบาทของ CSS :only-of-type Selector

ใช้ :only-of-type เพื่อจัดสไตล์ <p> ที่เป็น Tag <p> คนเดียว ของ Parent (อาจมี Tag อื่นอยู่แต่ <p> มีแค่ตัวเดียว)

ตัวอย่าง

<!DOCTYPE html>
<html>
<head>
    <style>
        p:only-of-type {
            background: orange;
            color: white;
        }
    </style>
</head>
<body>
    <div>
        <p>This is demo text 1.</p>
    </div>
    <div>
        <p>This is demo text 2.</p>
        <p>This is demo text 3.</p>
        <p>This is demo text 4.</p>
    </div>
</body>
</html>

ผลลัพธ์: <p> ใน <div> ตัวแรก (เป็น <p> คนเดียว) จะมีพื้นหลังส้ม ตัวอักษรสีขาว

ต่างจาก :only-child: :only-child ต้องเป็นลูกคนเดียวทุกประเภท ส่วน :only-of-type เรียกเฉพาะ Tag นั้นๆ