HTML & CSS

[HTML][CSS] :first-child, :first-of-type,:nth-child 선택자

권군이 2020. 12. 22. 14:59

1. :first-child 

 <ul>
        <li>리스트1</li>
        <li>리스트2</li>
        <li>리스트3</li>
        <li>리스트4</li>
    </ul>

리스트 4개를 생성. 여기다 실습을 해보겠다.

 

ul{list-style-type: none;}
ul>li{ width: 100px;height: 100px;}

ul>li:first-child{background: red;}

ul의 하위요소 li의 first-child에 background를 red로 적용.

 

:first-child 실습

:first-child >> 반드시 하위 요소가 첫번째에 있어야 한다.

 

리스트1위에 새로운 div를 생성한다면,,

 <ul>
        <div>div1</div>
        <li>리스트1</li>
        <li>리스트2</li>
        <li>리스트3</li>
        <li>리스트4</li>
    </ul>

:first-child 실습2

>>이렇게 li가 첫번째가 아니라 div이기 때문에 :first-child가 적용 안됨.

 

2. :first-of-type

 

div가 존재하는 상태에서 리스트1에 색을 넣으려면 :first-of-type을 쓰면 된다.

ul>li:first-of-type{background: red;}

:first-of-type >> 하위 요소 중 첫번째를 알아서 찾아감. 

 

3. :nth-child

<ul>
        <li>리스트1</li>
        <li>리스트2</li>
        <li>리스트3</li>
        <li>리스트4</li>
        <li>리스트5</li>
        <li>리스트6</li>
        <li>리스트7</li>
    </ul>
ul{list-style-type: none;}

ul>li:first-child{background: red;}
ul>li:nth-child(2){background: orange;}
ul>li:nth-child(3){background: yellow;}
ul>li:nth-child(4){background: green;}
ul>li:nth-child(5){background: blue;}
ul>li:nth-child(6){background: navy;}
ul>li:nth-child(7){background: purple;}

:nth-child() >> 괄호안에 숫자로 몇번째에 해당하는 요소인지 지정.

:nth-child 실습