[CSS] 선택자

조애옹·2025년 6월 13일

🔍 선택자란?

  • HTML 요소에 스타일을 적용할 때 어떤 요소를 선택할지 지정하는 문법

✅ 기본 선택자 (Basic Selectors)

선택자의미예시
A태그 선택div {}
.class클래스 선택.box {}
#idID 선택#header {}
A, B여러 요소 동시 선택h1, p {}
*전체 요소 선택* { margin: 0; }

✅ 결합자 (Combinators)

선택자의미예시
A BA 내부 모든 후손 Bdiv p {}
A > BA의 직계 자식 B만 선택ul > li {}
A + BA 바로 다음 형제 요소 Bh1 + p {}
A ~ BA 이후 모든 형제 요소 Bh1 ~ p {}

✅ 구조 선택자 (Structural Pseudo-classes)

선택자의미예시
:first-child첫 번째 자식 요소li:first-child {}
:last-child마지막 자식 요소li:last-child {}
:only-child유일한 자식 요소div:only-child {}
:nth-child(n)n번째 자식li:nth-child(2) {}
:nth-last-child(n)뒤에서 n번째 자식li:nth-last-child(1)

✅ 타입 기반 선택자 (Type Pseudo-classes)

선택자의미예시
:first-of-type형제 중 같은 태그의 첫 번째 요소p:first-of-type {}
:last-of-type같은 타입 중 마지막 요소li:last-of-type {}
:nth-of-type(n)같은 태그 중 n번째 요소li:nth-of-type(2) {}
:nth-of-type(odd)같은 태그 중 홀수 번째tr:nth-of-type(odd) {}
:nth-of-type(even)같은 태그 중 짝수 번째tr:nth-of-type(even) {}
:empty내용(텍스트+태그)이 없는 요소p:empty {}
:not(X)X에 해당하지 않는 요소div:not(.active) {}

✅ 속성 선택자 (Attribute Selectors)

선택자의미예시
A[attribute]해당 속성이 존재하는 A 요소input[required] {}
A[attribute="value"]정확히 일치하는 속성값input[type="text"] {}
A[attribute^="value"]해당 속성이 value로 시작a[href^="https"] {}
A[attribute$="value"]해당 속성이 value로 끝남img[src$=".jpg"] {}
A[attribute*="value"]해당 속성에 value 포함됨div[class*="item"] {}

💡 TIPS

profile
아자잣

0개의 댓글