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

บทบาทของ CSS :only-child Selector

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

ตัวอย่าง

<!DOCTYPE html>
<html>
<head>
    <style>
        p:only-child {
            background: orange;
        }
    </style>
</head>
<body>
    <h1>Heading</h1>
    <div>
        <p>This is a paragraph.</p>
    </div>
    <div>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
    </div>
</body>
</html>

ผลลัพธ์: <p> ใน <div> ตัวแรก (ลูกคนเดียว) จะมีพื้นหลังส้ม ส่วนใน <div> ตัวที่สอง (มี 3 ลูก) จะไม่ได้รับผล