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

Descendant Selectors ใน CSS (ตัวเลือกแบบลูกหลาน)

CSS Descendant Selector ใช้เลือกองค์ประกอบที่เป็นลูกหลาน (descendant) ขององค์ประกอบแรก โดยชื่อองค์ประกอบตรงกับตัวเลือกที่สอง

ไวยากรณ์ (Syntax)

element element {
  /* declarations */
}

ตัวอย่างที่ 1: นested div หลายชั้น

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      float: right; margin: 25px; padding: 5px;
      width: 80px; height: 80px; border: solid aqua;
    }
    div div {           /* div ลูกของ div */
      border-color: blue;
      border-radius: 50%;
    }
    div div div {       /* div หลานของ div */
      border-color: orange;
      border-radius: unset;
    }
  </style>
</head>
<body>
  <div>
    <div>
      <div></div>
    </div>
  </div>
</body>
</html>

ผลลัพธ์

Descendant Selectors ใน CSS (ตัวเลือกแบบลูกหลาน)

ตัวอย่างที่ 2: นested list (ol > ul > li)

<!DOCTYPE html>
<html>
<head>
  <style>
    li li { background-color: lightsteelblue; }
  </style>
</head>
<body>
  <ol>
    <li></li>
    <ul>
      <li>
        <ul>
          <li></li>
        </ul>
      </li>
    </ul>
    <li></li>
  </ol>
</body>
</html>

ผลลัพธ์

Descendant Selectors ใน CSS (ตัวเลือกแบบลูกหลาน)

ความแตกต่าง Descendant vs Child Selector

Selectorรูปแบบคำอธิบาย
Descendantdiv pเลือก p ทุกตัวภายใน div (ลูก หลาน เหยื่อ)
Childdiv > pเลือก p ที่เป็นลูกโดยตรงของ div เท่านั้น