본문 바로가기

웹 프론트 엔드

CSS 선택자 - 가상 클래스 선택자 : child & of-type

 

 

가상 클래스 선택자 (Pseudo-Class Selector)

   - 선택자 뒤에 조건을 추가한 더 디테일한 선택자입니다.

   - 선택자:[조건] 의 형식으로 작성합니다.

 

 

first-child

/* Pseudo-Class Selector*/
/* Style*/
li{
    color: green;
}
/* 1. first-child */
li:first-child{
    color: red;
}



/* HTML */
<h2>Movie List</h2>
<ul>
	<li class="movie">ToyStory</li>
	<li class="movie">Zootopia</li>
	<li class="movie">Inside Out</li>
	<li class="movie">Coco</li>
	<li class="movie">Finding Nemo</li>
</ul>
<h2>Cafe Menu</h2>
<ol>
	<li>Americano</li>
	<li>Latte</li>
	<li>Hot Choco</li>
</ol>

실행 결과

   > 모든 태그 내에 첫번째 자식태그인 경우 적용된다.

 

last-child

first-child를 last-child로 바꿔 실행한 것

   > 모든 태그 내에 마지막 자식태그인 경우 적용된다.

 

nth-child( )

ul li:nth-child(3){
    color: red;
}
ol li:nth-child(2){
    color: blue;
}

실행화면

   > nth-child 뒤에 괄호를 적고 그 안에 순서를 지정하여 사용합니다.

ul li:nth-child(2n){
    color: red;
}
ol li:nth-child(even){
    color: blue;
}

실행화면

   > odd 나 even 같은 문자열 또는 2n-1 등의 수식으로 여러개의 자식들을 묶어서 선택할 수도 있습니다.

 

 

 

first-of-type & last-of-type & nth-of-type()

   - first-child & last-child & nth-child() 과의 차이점

/* CSS Style */
ul li:nth-child(even){
    color: red;
}

ol li:nth-of-type(even){
    color: blue;
}

/* HTML */

<h2>nth-child() 적용</h2>
      <ul>
        <div>첫번째 자식은 div입니다.</div>
        <li class="movie">두번째 자식은 li입니다.</li>
        <li class="movie">세번째 자식은 li입니다.</li>
        <div>네번째 자식은 div입니다</div>
        <p>다섯번째 자식은 p입니다.</p>
        <li class="movie">여섯번째 자식은 li입니다.</li>
        <li class="movie">일곱번째 자식은 li입니다.</li>
      </ul>
      
      <h2>nth-of-type() 적용</h2>
      <ol>
        <div>첫번째 자식은 div입니다.</div>
        <li class="movie">두번째 자식은 li입니다.</li>
        <li class="movie">세번째 자식은 li입니다.</li>
        <div>네번째 자식은 div입니다</div>
        <p>다섯번째 자식은 p입니다.</p>
        <li class="movie">여섯번째 자식은 li입니다.</li>
        <li class="movie">일곱번째 자식은 li입니다.</li>
      </ol>

      > child는 전체 자식 태그들 중에서 정하는 반면 of-type은 해당 타입들 중에서 정한다.

실행 화면

   - 둘 다 짝수번째만을 염색했다.

   - nth-child는 div, p, li를 모두 고려하여 짝수번째 자식이 li 태그인 경우에 적용되었습니다.

      > 따라서 두번째, 여섯번째 자식은 li 태그이므로 적용되었지만,

         네번째 자식은 div태그였으므로 스타일이 적용되지 않았습니다.

 

   - nth-of-type은 li 태그만을 고려하여 짝수번째 li 태그에 적용시켰습니다.

      > 세번째 자식인 li태그는 전체 태그중에선 세번째 자식이지만, li 태그중에서 두번째 태그이므로 적용되었습니다.

      > 일곱번째 자식인 li 태그 또한 마찬가지로 li 태그 중 네번째 태그이므로 적용되었습니다.