Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발일기

[css] :first-child, :last-child, :nth-child(n) / 동적 가상 클래스 본문

HTML, CSS

[css] :first-child, :last-child, :nth-child(n) / 동적 가상 클래스

화영강 2022. 10. 19. 15:21
구조 가상클래스 - :first-child, :last-child, :nth-child(n)

 

<실습문제1-3번>

구조가상클래스로 풀려고 했는데 도저히 안되서

    <div style="background-color: deepskyblue;">deepskyblue(#00BFFF)</div>
    <div style="background-color: brown;">brown(#A52A2A)</div>
    <div style="background-color: fuchsia;">fuchsia(#FF00FF)</div>
    <div style="background-color: darkorange;">darkorange(#FF8C00)</div>
    <div style="background-color: darkcyan;">darkcyan(#008B8B)</div>
    <div style="background-color: olivedrab;">olivedrab(#6B8E23)</div>

결국 이런식으로 각각에 스타일을 줬다.

 

 

구조 가상클래스로 주기 위해서는

 

1. div들을 div로 한번 묶어서

div div:first-child { }

(반드시 div div처럼 상위, 하위 요소를 다 입력해야 에러가 생기지 않는다)

이런식으로 주거나

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        div {
            margin-left: 30px;
            margin-right: 30px;
            margin-bottom: 10px;
            color: white;
        }

        div div:first-child {
            background-color: deepskyblue;
        }

        div div:nth-child(2) {
            background-color: brown;
        }

        div div:nth-child(3) {
            background-color: fuchsia;
        }

        div div:nth-child(4) {
            background-color: darkorange;
        }

        div div:nth-child(5) {
            background-color: darkcyan;
        }

        div div:last-child {
            background-color: olivedrab;
        }
    </style>
</head>
<body>
    <h3>CSS3 색 활용</h3>
    <hr>
    <div>
        <div>deepskyblue(#00BFFF)</div>
        <div>brown(#A52A2A)</div>
        <div>fuchsia(#FF00FF)</div>
        <div>darkorange(#FF8C00)</div>
        <div>darkcyan(#008B8B)</div>
        <div>olivedrab(#6B8E23)</div>
    </div>
</body>
</html>

 

 

2. :nth-child(n)를 이용해서

:nth-child(3) 이 첫번째 div

:nth-child(4) 는 두번째 div

...

이렇게도 할 수 있다.

 

 

 

 

동적 가상클래스

:hover   마우스가 올라갈 때

:active   마우스로 누르고 있을 때

:focus   폼 요소가 키보드나 마우스 클릭이 되었을 때

:link   방문하지 않은 링크

:visited   방문한 링크

:first-line   블록형태그(<p>, <div>)의 첫 라인

:first-letter   블록형태그(<p>, <div>)의 첫 글자

:checked   checkbox에서 체크된 항목