λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
🌌 | WEB DEV/HTML CSS

CSS κ°€μƒν΄λž˜μŠ€ (2)_μˆœμ„œ κ°€μƒν΄λž˜μŠ€[1] (nth-child, nth-of-type)

by KASSID 2022. 1. 7.

λͺ©μ°¨

    728x90

    μ΄λ²ˆμ—λŠ” μˆœμ„œλ₯Ό λΆ€μ—¬ν•˜λŠ” κ°€μƒν΄λž˜μŠ€λ₯Ό μ•Œμ•„λ³΄μ•˜λ‹€.

     

     nth-child 

    nth-childλŠ” μˆœμ„œλ₯Ό λΆ€μ—¬ν•˜λŠ” κ°€μƒν΄λž˜μŠ€μ΄λ‹€.

    (κ°€μž₯ λŒ€ν‘œμ μΈ μˆœμ„œλΆ€μ—¬ κ°€μƒν΄λž˜μŠ€)

     

    μ‚¬μš©λ²•

    μ„ νƒμž:nth-child(μˆœμ„œ)

    (λ„μ–΄μ“°κΈ°λŠ” μ—­μ‹œ X)

     

    μ˜ˆμ‹œ

    <div class="box">
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>

     

    .box {
        border: 5px solid #000;
        width: 1000px;
        text-align: center;
    }
    .box div {
        border: 5px solid #000;
        margin: 10px;
        width: 200px;
        height: 200px;
        display: inline-block;
    }

    μœ„μ™€ 같이 λΆ€λͺ¨μš”μ†ŒμΈ 'box'ν΄λž˜μŠ€μ— 4개의 μžμ‹μš”μ†Œκ°€ μžˆλ‹€.

     

    이 4개의 μš”μ†Œμ— μˆœμ„œλ₯Ό 뢀여해보면

     

    .box div:nth-child(1) {
        background-color: dodgerblue;
    }
    .box div:nth-child(2) {
        background-color: red;
    }
    .box div:nth-child(3) {
        background-color: blueviolet;
    }
    .box div:nth-child(4) {
        background-color: gold;
    }

    μ™Όμͺ½λΆ€ν„° 1, 2, 3, 4번째둜 μˆœμ„œκ°€ λΆ€μ—¬κ°€ λ˜μ—ˆλ‹€!

     

     

    ν•˜μ§€λ§Œ μ£Όμ˜ν•  점이 μžˆλ‹€.

    <div class="box">
        <p>hello</p>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>

     

    CSS뢀뢄은 λ³€κ²½ν•˜μ§€ μ•Šκ³  μžμ‹μš”μ†Œμ— pνƒœκ·Έλ₯Ό μΆ”κ°€ν•˜μ˜€λ‹€.

    μžμ‹μš”μ†Œ 쀑 divνƒœκ·Έμ— μˆœμ„œλ₯Ό λΆ€μ—¬ν•˜μ˜€μ§€λ§Œ,

    μ—‰λš±ν•œ pνƒœκ·Έλ„ ν•¨κ»˜ 카운트λ₯Ό 해버렸닀.

    (2, 3, 4, 5번으둜 μˆœμ„œκ°€ λ°€λ¦Ό)

     

    즉, nth-childλŠ” 단지 μΆœν˜„ μˆœμ„œλ₯Ό 따진닀.

    (νƒœκ·Έλ₯Ό κ΅¬λΆ„ν•˜μ§€ μ•Šκ³ !)


    이λ₯Ό ν•΄κ²°ν•˜κΈ° μœ„ν•œ λ‹€λ₯Έ 방법이 μžˆλ‹€.

     

    nth-of-type

    nth-of-type은 νƒœκ·Έλ₯Ό κ΅¬λΆ„ν•˜μ—¬ μˆœμ„œλ₯Ό λΆ€μ—¬ν•œλ‹€.

    .box div:nth-of-type(1) {
        background-color: dodgerblue;
    }
    .box div:nth-of-type(2) {
        background-color: red;
    }
    .box div:nth-of-type(3) {
        background-color: blueviolet;
    }
    .box div:nth-of-type(4) {
        background-color: gold;
    }

    μœ„μ²˜λŸΌ ν•΄λ‹Ή μ„ νƒμžμ—κ²Œλ§Œ μˆœμ„œκ°€ 적용이 된 것을 μ•Œ μˆ˜μžˆλ‹€.

    λŒ“κΈ€