CLASS web

CSS

CSS 셀렉터 5 (위치 선택자)

CSS 셀렉터 5(선택자)

위치 가상 클래스

태그의 위치를 지정하여 선택할 수 있습니다. nth-child(위치)를 사용합니다.
예를 들어 5번째에 위치한 태그를 선택한다면 nth-child(5)를 선택합니다.

위치 가상 클래스 사용방법

선택자:nth-child(n){속성:값}

해봅시다. ^^

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>위치 가상 클래스</title>
<style>
    p:nth-child(3){color:skyblue}
</style>
</head>
<body>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
</body>
</html>

결과는 바로 아래에서 확인할 수 있습니다.







3번째에 위치한 p태그에만 CSS가 적용되었네요. ^^

특정 태그 안에서 3번째에 위치한 p태그를 선택하면 다음과 같겠죠?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>위치 가상 클래스</title>
<style>
    aside p:nth-child(2){color:skyblue}
</style>
</head>
<body>
    <section>
        <p>pinkcoding</p>
        <p>pinkcoding</p>
        <p>pinkcoding</p>
    </section>
    <aside>
        <p>tomodevel</p>
        <p>tomodevel</p>
        <p>tomodevel</p>
    </aside>
</body>
</html>

결과는 바로 아래에서 확인할 수 있습니다.







이번엔 역순으로 마지막에서 순서를 정하는 방법애 대해 알아보겠습니다.
nth-last-child(n)을 사용합니다.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>위치 가상 클래스</title>
<style>
    p:nth-last-child(2){color:skyblue}
</style>
</head>
<body>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
</body>
</html>

결과는 바로 아래에서 확인할 수 있습니다.







마지막에서 2번째에 있는 p태그를 선택했으므로 끝에서 2번째에 있는 태그에 CSS가 적용되었습니다.

처음오는 요소 마지막에 오는 요소 선택하기

위에서 사용한 태그 선택은 태그가 몇번째 인지 알아야 했습니다.
이번엔 오직 처음오는 것과 마지막에 오는 것만 선택하는 선택자입니다.
first-of-type과 last-of-type을 사용합니다.
이름만 들어도 용도를 알겠죠?

선택자:first-of-type{속성:값}
선택자:last-of-type{속성:값}

그럼 예제를 통하여 처음과 마지막 태그에만 색을 적용해볼게요.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>위치 가상 클래스</title>
<style>
    p:first-of-type{color:skyblue}
    p:last-of-type{color:hotpink}
</style>
</head>
<body>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
    <p>pinkcoding</p>
</body>
</html>

결과는 바로 아래에서 확인할 수 있습니다.







그럼 다음시간에 더 많은 셀렉터에 대해 알아봅시다.





댓글 0개

정렬기준

PinkCoding

PinkCoding

X

PinkCoding

Web Scratch Pad

X

loading

            
            
        

컨텐츠로 돌아가기