[HTML&CSS] nth-child, first-child, last-child

2020. 11. 26. 18:54HTML&CSS&JavaScript

<HTML>

<section>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</section>

<CSS>

div {
    width:15%; /* 부모 엘리먼트 너비 기준 */
    height:100px;
    background-color:red;
    display:inline-block;
}

div:first-child {       /*첫번째 자식*/
    background-color:blue;
}

div:nth-child(2) {       /*n(2)번째 자식*/
    background-color:gold;
}

div:last-child {          /*마지막 자식*/
    background-color:green;
}

div:nth-last-child(2) {      /*마지막에서 n(2)번째 자식*/
    background-color:pink;
}

codepen.io/jangka44/pen/xJEeag

<응용-무지개>

section {
    text-align:center;
}

section > div {
    width:13%;
    height:100px;
    background-color:red;
    display:inline-block;
}

section > div:nth-child(7n + 2) {
    background-color:orange;
}

section > div:nth-child(7n + 3) {
    background-color:yellow;
}

section > div:nth-child(7n + 4) {
    background-color:green;
}

section > div:nth-child(7n + 5) {
    background-color:blue;
}

section > div:nth-child(7n + 6) {
    background-color:navy;
}

section > div:nth-child(7n + 7) {
    background-color:purple;
}

codepen.io/jangka44/pen/aboeyRQ