[CSS] 선택자

Coastby·2022년 8월 15일
0

<head> 내 <style> 태그 또는 분리된 파일에 적용 시

선택자의 종류

  • tag 선택자 : 문서 내 지명된 모든 태그에 적용
span { color: blue; }

div {
  margin: 24px;
  padding: 48px;
  background-color: pink;
}
  • class 선택자 : 문서 내 다수 요소에 동일하게 적용될 수 있는 class 속성에 적용
  <h1 class="important">할 일 목록</h1>
  <ul>
    <li class="important">빨래</li>
    <li class="finished">30분 운동</li>
    <li>마트 장보기</li>
    <li class="finished">책 50페이지 이상 읽기</li>
    <li class="finished important">코딩 강좌 실습</li>
  </ul>
.finished { color: skyblue; }
.important { text-decoration: underline; }

/* 특정 태그에 해당 클래스가 있을 때 */
li.important { background-color: yellow; }

/* 하나 이상의 클래스 */
.important.finished { font-style: italic; }
  • id 선택자 : 문서 내 유일한 요소에 적용될 수 있는 id 속성에 적용
    하나 이상 사용 시 자바스크립트 등에서 오류 발생시킬 수 있다.
  <section id="intro">
    소개 섹션
  </section>
  <section id="board">
    게시판 섹션
  </section>
section { padding: 32px; }

/* 아래부터 */
#intro { background-color: yellowgreen; }
#board { background-color: pink; }
  • attr (속성) 선택자 : 태그의 속성과 그 값에 따라 적용
/* <a> elements with a title attribute */
a[title] {
  color: purple;
}

/* <a> elements with an href matching "https://example.org" */
a[href="https://example.org"] {
  color: green;
}

/* <a> elements with an href containing "example" */
a[href*="example"] {
  font-size: 2em;
}

/* <a> elements with an href ending ".org" */
a[href$=".org"] {
  font-style: italic;
}

/* <a> elements whose class attribute contains the word "logo" */
a[class~="logo"] {
  padding: 2px;
}

[attr]
attr이라는 이름의 특성을 가진 요소를 선택합니다.
[attr=value]
attr이라는 이름의 특성값이 정확히 value인 요소를 선택합니다.
[attr~=value]
attr이라는 이름의 특성값이 정확히 value인 요소를 선택합니다. attr 특성은 공백으로 구분한 여러 개의 값을 가지고 있을 수 있습니다.
[attr|=value]
attr이라는 특성값을 가지고 있으며, 그 특성값이 정확히 value이거나 value로 시작하면서 -(U+002D) 문자가 곧바로 뒤에 따라 붙으면 이 요소를 선택합니다. 보통 언어 서브코드(en-US, ko-KR 등)가 일치하는지 확인할 때 사용합니다.
[attr^=value]
attr이라는 특성값을 가지고 있으며, 접두사로 value가 값에 포함되어 있으면 이 요소를 선택합니다.
[attr$=value]
attr이라는 특성값을 가지고 있으며, 접미사로 value가 값에 포함되어 있으면 이 요소를 선택합니다.
[attr*=value]
attr이라는 특성값을 가지고 있으며, 값 안에 value라는 문자열이 적어도 하나 이상 존재한다면 이 요소를 선택합니다.
[attr operator value i]
괄호를 닫기 전에 i 혹은 I를 붙여주면 값의 대소문자를 구분하지 않습니다. (ASCII 범위 내에 존재하는 문자에 한해서 적용됩니다)
[attr operator value s]
괄호를 닫기 전에 s 혹은 S를 붙여주면 값의 대소문자를 구분합니다. (ASCII 범위 내에 존재하는 문자에 한해서 적용됩니다)

  <label for="ip-id">아이디</label>
  <input id="ip-id" type="text"/>
  <br>
  <label for="ip-pw">비밀번호</label>
  <input id="ip-pw" type="password"/>
  <br>
  <label for="ip-nm">이름</label>
  <input id="ip-nm" type="text"/>
label {
  display: inline-block;
  width: 80px;
}

/* 아래부터 */
input[type=text] { background-color: skyblue; }
label[for=ip-id] { color: blue; }

type 특성은 주로 <input> 요소에 사용하므로, HTML 명세는 type의 대소문자를 구분하지 않고 선택하도록 요구하고 있습니다. 그러므로 <ol>의 type을 특성 선택자로 선택할 땐 대소문자 구분 수정자를 지정하지 않으면 동작하지 않습니다.

<ol type="A">
  <li>Example list</li>
</ol>
/* List types require the case sensitive flag due to a quirk in how HTML treats the type attribute. */
ol[type="a"] {
  list-style-type: lower-alpha;
  background: red;
}

ol[type="a" s] {
  list-style-type: lower-alpha;
  background: lime;
}

ol[type="A" s] {
  list-style-type: upper-alpha;
  background: lime;
}

👉 result
a.Example list


결합자

  • 자손 결합자 : 내부의 모든 요소들을 선택
  <div class="outer">
    <div>
      <div>
        <div></div>
      </div>
    </div>
    <div>
      <div></div>
      <div></div>
    </div>
  </div>
  
div {
  padding: 24px;
  border: 1px solid black;
  background-color: white;
}
.outer { background-color: green; }

/* 앞 선택자 뒤에 스페이스를 둠으로써 자손 요소들을 선택 */
.outer div {
  background-color: yellow;
}
  
  • 자식 결합자 : 바로 안 단계 요소들을 선택
  /* 자손 결합자 코드에서 수정 */
  /* 빈 공백이 아닌 > 을 넣어주면 자식(1촌 자손)만 선택 */
  .outer > div {
    background-color: yellow;
  }
  • 인접형제 (바로 다음 동생) 결합자
<div>첫줄</div>
<div>둘째줄</div>
<div class="selected">선택된 줄</div>
<div>넷째줄</div>
<div>다섯째 줄</div>
div {
  padding: 12px 24px;
  border-top: 1px solid black;
}
.selected {
  border-top: 0;
  color: white;
  background-color: dodgerblue;
}

/* 아래부터 */
.selected + div { border-top: 0; }
  • 전체 선택자 : 모든 태그에 적용
div { background-color: white; }

/* 특정 요소의 자손/자식으로 지정하지 않으면 body 등에도 적용 */
section * {
  display: inline-block;
  background-color: orange;
  padding: 24px;
}

pseudo(가상) 클래스

의사 클래스 (가상 클래스)는 선택자에 추가하는 키워드로, 선택한 요소가 특별한 상태여야 만족할 수 있다. 의사 클래스를 사용하면 문서 트리 콘텐츠와 관련된 경우 뿐만 아니라 탐색기 히스토리 (:visited 등), 컨텐츠의 상태 (특정 폼 요소에 적용한 :checked), 마우스의 위치 (커서가 마우스 위인지 아닌지 알 수 있는 :hover등) 처럼 외부 인자와 관련된 경우에도 스타일을 적용할 수 있다.

https://developer.mozilla.org/ko/docs/Web/CSS/Pseudo-classes

  • 부정 가상 클래스
.blue { color: blue; }
.underline { text-decoration: underline; }

/* 아래부터 */
.underline:not(.blue) { color: red; }
.underline:not(.blue):not(li) { color: inherit; }
  • 순서 관련 가상 클래스
/* 아래부터 */
ul li:first-child { border-top: 2px solid black; }
ul li:last-child { border-bottom: 2px solid black; }
ul li:nth-child(3) { color: purple; }
ul li:nth-child(even) { background-color: #eee; }
ul li:nth-child(3n+1) { text-decoration: underline; }

우선순위

  • 인라인 스타일 > id 선택자 > class 선택자 > 태그 선택자
  • 구체적일수록 높은 순위로 적용된다.
  • 같은 우선순위라면 다음에 (더 아랫줄에) 오는 것이 덮어쓴다.
profile
훈이야 화이팅

0개의 댓글