CSS 선택자

heejung·2022년 2월 24일
0

선택자의 종류

tag 선택자

  • 문서 내 지명된 모든 태그에 적용
<span>파랑색 글자</span>입니다.
span { color: blue; }

class 선택자

  • 문서 내 다수 요소에 동일하게 적용 가능한 class 속성에 따라 적용
<h1 class="important">할 일 목록</h1>
<ul>
    <li class="important">빨래</li>
<ul>
.important { text-decoration: underline; }

id 선택자

  • 문서 내 유일한 요소에 적용될 수 있는 id 속성에 따라 적용
<section id="intro">
    소개 섹션
  </section>
  <section id="board">
    게시판 섹션
  </section>
#intro { background-color: yellowgreen; }
#board { background-color: pink; }

속성 선택자

  • 태그의 속성과 그 값에 따라 적용
<label for="ip-id">아이디</label>
  <input id="ip-id" type="text"/>
input[type=text] { background-color: skyblue; }
label[for=ip-id] { color: blue; }


결합자

자손 결합자

  • 내부의 모든 요소들을 선택 (자식-손자-...)
  <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;
}

자식 결합자

  • 바로 안 단계의 요소들을 선택 (직계 자식만)
  <div class="outer">
    <div>
      <div>
        <div></div>
      </div>
    </div>
    <div>
      <div></div>
      <div></div>
    </div>
  </d
div {
  padding: 24px;
  border: 1px solid black;
  background-color: white;
}
.outer { background-color: green; }

/* 자식 결합자: 부모 뒤에 '>' */
.outer > div {
  background-color: yellow;
}

전체 선택자

  • 모든 태그에 적용
  <section>
    <h1>제목</h1>
    <span>span 요소</span>
    <div>
      요소
      <div>더 안쪽 요소</div>
    </div>
  </section>
/* 특정 요소의 자손·자식으로 지정하지 않으면 body 등에도 적용 */
section * {
  display: inline-block;
  background-color: orange;
  padding: 24px;
}


psudo(가상)클래스

부정 가상 클래스

  <h1 class="underline">부정 가상 클래스 사용예</h1>
  <ul>
    <li>특성 없음</li>
    <li class="blue">파랑글씨</li>
    <li class="blue underline">파랑글씨에 및줄</li>
    <li class="underline">파랑글씨는 아닌데 및줄</li>
  </ul>
.blue { color: blue; }
.underline { text-decoration: underline; }

/* 부정 가상 클래스 */
.underline:not(.blue) { color: red; }
.underline:not(.blue):not(li) { color: green; }

순서 관련 가상 클래스

  <ul>
    <li>첫번째 글</li>
    <li>두번째 글</li>
    <li>세번째 글</li>
    <li>네번째 글</li>
    <li>다섯번째 글</li>
    <li>여섯번째 글</li>
    <li>일곱번째 글</li>
    <li>여덟번째 글</li>
  </ul>
ul { padding: 0; }
ul li {
  list-style: none;
  padding: 8px 16px;
  border-top: 1px solid lightgray;
}

/* 순서 관련 가상 클래스 */
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; }

마우스오버 가상 클래스

<button class="blue-button">클릭</button>
.blue-button {
  font-size: 1em;
  padding: 16px 24px;
  color: white;
  background-color: dodgerblue;
  border: 0;
  cursor: pointer;
  border-radius: 4px;
}

/* 마우스오버: hover */
.blue-button:hover {
  background-color: darkblue;
}

profile
프론트엔드 공부 기록

0개의 댓글