[CSS] 의사클래스 - first-child, last-child, first-of-type, last-of-type


Study/Javascript, Jquery, CSS  2020. 1. 16. 23:05

안녕하세요. 명월입니다.


이 글은 CSS에서의 의사클래스(first-child, last-child, first-of-type, last-of-type)에 대한 글입니다.

first-child와 first-of-type 에 대해서는 nth-child(1)와 nth-of-type(1)과 같은 의미의 의사 클래스입니다.

의사클래스는 오브젝트의 속성이나 태그를 이용한 선택이이 아닌 html의 배치에 따른 선택자이기 다른 라이브러리나 javascript로 동적으로 작성된 오브젝트에 관해 사용되는 선택자이기도 합니다.


링크 - [CSS] 의사클래스 - nth-child, nth-of-type, nth-last-child, nth-last-of-type

<!DOCTYPE html>
<html>
 <head>
  <style>
    table{
      border-spacing:0px;
      padding:0px;
    }
    td, th{
      width:200px;
    }
  </style>
 </head>
 <body>
  <table>
    <tbody>
      <tr>
        <th>1</th>
        <td>2</td>
      </tr>
      <tr>
        <th>3</th>
        <td>4</td>
      </tr>
    </tbody>
  </table>
 </body>
</html>

위 예제를 보면 table태그에 제가 테두리(border)를 설정하지 않았습니다. first-child와 first-of-type을 이용해서 좀 멋지게(?) 볼더를 설정하기 위해서 입니다.

/* td태그와 th태그의 오른쪽과 아래의 태두리는 검은색으로 표시 */
td, th {
  border-right:3px solid #000;
  border-bottom:3px solid #000;
}
/* 첫번째가 tr인 태그의 td  */
tr:first-child > td {
  border-top:3px solid red;
}
/* 첫번째 tr인 태그의 th */
tr:first-of-type > th {
  border-top:3px solid blue;
}
/* 첫번째가 th인 태그 */
th:first-child {
  border-left:3px solid orange;
}
/* 첫번째 td인 태그 */
td:first-of-type {
  border-left:3px solid green;
}

먼저 전체적으로 오른쪽과 아래는 검은색 태두리로 그려집니다.

두번째 style지시자는 첫번째가 tr인 태그는 1과 2가 있는 tr태그 입니다. 그 tr태그의 td태그인 2를 선택합니다. 그러므로 2번의 상단이 빨간색이 됩니다.

세번째 style지시자는 첫번째 tr 태그도 역시 1과 2가 있는 tr태그입니다. 그 tr태그의 th태그인 1를 선택합니다. 그러므로 1번의 상단이 파란색이 됩니다.

네번째는 첫번째가 th인 태그는 1과 3번입니다. 1과 3번은의 왼쪽 테두리는 오렌지가 됩니다.

다섯번째는 첫번째 td태그이므로 2와 4번입니다. 이유는 그 앞은 th태그이므로 td로써는 첫번째입니다. 2와 4의 오른쪽 태그는 초록색이 됩니다.

/* 마지막이 td인 태그 */
td:last-child {
  background-color: yellow;
}
/* 마지막 th 태그 */
th:last-of-type {
  background-color: aqua;
}

첫번째 style지시자는 td가 마지막인 태그이므로 2와 4번이 됩니다. 2와 4는 노락색 바탕이 됩니다.

두번째 style지시자는 마지막 th이므로 1과 3번이 됩니다. 1과 3은 마지막 태그는 아니지만 th로써는 마지막이기 때문입니다. 1과 3은 아쿠아색 바탕이 됩니다.

여기까지 CSS에서의 의사클래스(first-child, last-child, first-of-type, last-of-type)에 관한 설명이었습니다.


궁금한 점이나 잘못된 점이 있으면 댓글 부탁드립니다.