Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Pseudo-class :first-child trong CSS

CSS :first-child pseudo-class chọn một phần tử là phần tử con đầu tiên của một phần tử cha khác.

Cú pháp

:first-child {
  /*declarations*/
}

Ví dụ 1: Bỏ border-left cho first child trong table

<!DOCTYPE html>
<html>
<head>
<style>
  table { margin: auto; padding: 10px; border: hsl(54, 100%, 50%) solid 13px; border-radius: 6px; text-align: center; }
  td, th { border-left: 2px solid black; border-top: 3px solid black; }
  td:first-child, th:first-child { border-left: none; }
  th { background-color: lightblue; border-top: none; }
  caption { margin-top: 3px; background-color: purple; caption-side: bottom; color: white; border-radius: 20%; }
</style>
</head>
<body>
  <table>
    <caption>MCA Syllabus</caption>
    <tr> <th colspan="4">Subjects</th> </tr>
    <tr> <td>C</td> <td>C++</td> <td>Java</td> <td>C#</td> </tr>
    <tr> <td>MySQL</td> <td>PostgreSQL</td> <td>MongoDB</td> <td>SQLite</td> </tr>
  </table>
</body>
</html>

Kết quả

Trước khi dùng first-child pseudo-class selector:

Pseudo-class :first-child trong CSS

Sau khi dùng first-child pseudo-class selector:

Pseudo-class :first-child trong CSS

Ví dụ 2: :first-child trên list items

<!DOCTYPE html>
<html>
<head>
<style>
  * { font-size: 1.1em; list-style: circle; }
  li:first-child { background-color: seashell; font-family: cursive; }
  li:nth-child(2) { background-color: azure; font-family: "Brush Script Std", serif; }
  li:last-child { background-color: springgreen; font-family: "Gigi", Arial; }
</style>
</head>
<body>
  <h2>Apache Spark</h2>
  <ul>
    <li>Apache Spark is a lightning-fast cluster computing technology, designed for fast computation. </li>
    <li>It is based on Hadoop MapReduce.</li>
    
  • It extends the MapReduce model to efficiently use it for more types of computations. </li> </ul> </body> </html>
  • Kết quả

    Pseudo-class :first-child trong CSS

    Lưu ý quan trọng:

    • :first-child chọn phần tử là con đầu tiên của phần tử cha, bất kể loại thẻ
    • Khác với :first-of-type - chọn phần tử đầu tiên của loại đó trong cha
    • Ví dụ: p:first-child chỉ khớp nếu <p> là con đầu tiên của cha. Nếu con đầu tiên là <h1> thì không khớp.

    So sánh:

    SelectorChọn gì?Ví dụ khớp
    :first-childCon đầu tiên của parent (bất kỳ loại)Div đầu tiên trong container
    :first-of-typeCon đầu tiên CỦA LOẠI ĐÓ của parentP đầu tiên trong container (dù h1 ở trước)
    :nth-child(1)Tương đương :first-childCùng ý nghĩa
    :nth-of-type(1)Tương đương :first-of-typeCùng ý nghĩa

    Ứng dụng thực tế: Bỏ border đầu/cuối, styling đặc biệt cho item đầu tiên trong list/menu/card grid, typography (drop cap).