Development/HTML & CSS

[CSS] CSS 결합자 (Feat. hover시 다른 요소에 스타일 주기)

이쥬딩 2021. 2. 1. 21:10
728x90

💁‍♀️ 들어가기 전에

<html>
  <div class="hover">Hover</div>
  <div class="target">Target</div>
</html>

위와 같은 HTML 코드에서 hover class에 hover시 target class의 폰트색상을 변경하고 싶다면,

즉, 한 요소를 선택했을 때 다른 요소에 스타일을 주고 싶다면 CSS 결합자를 알면 된다.

CSS 결합자

CSS 결합자는 선택자가 결합된 걸 말한다.

<html>
  <div class="parent">parent
     <div class="child">child</div>
  </div>
</html>
.parent .child {
  color: red;
}

위 와 같이 parent 클래스를 선택하고 그 선택 기반으로 child 클래스를 선택한 경우를 말한다.

이런 결합자는 몇 가지 종류가 있다.

자손 결합자

  • 첫 번째 요소의 자손인 노드를 선택

  • 공백 사용

.parent .child {
  color: red;
}

parent 클래스 안에 있는 모든 child 클래스가 선택된다.

<html>
  <div class="parent">parent
     <div class="child">child</div>
     <div class="child">child</div>
     <div>
     	<div class="child">child</div>
     <div>
  </div>
</html>

자손 결합자이므로 최상위 child 클래스만 선택되는게 아니라 child 클래스 3개가 다 선택된다.

자식 결합자

  • 첫 번째 요소의 바로 아래 자식인 노드를 선택

  • > 사용

.parent > .child {
  color: red;
}

parent 클래스 안에 바로 아래 자식인 child 클래스가 선택된다.

<html>
  <div class="parent">parent
     <div class="child">child</div>
     <div class="child">child</div>
     <div>
     	<div class="child">child</div>
     <div>
  </div>
</html>

자식 결합자이므로 parent 클래스 바로 아래에 있는 2개의 child 클래스만 선택된다.

 

일반 형제 결합자

  • 첫 번째 요소를 뒤따르면서 같은 부모를 공유하는 두 번째 요소를 선택

  • ~ 사용

.brother ~ .sister {
  color: red;
}

brother 클래스와 형제인 sister 클래스가 선택된다.

<html>
  <div class="brother">brother</div>
  <div class="sister">
    sister
  </div>
  <div class="brother">brother</div>
</html>

형제 결합자 이므로 brother 클래스와 서로 같은 부모 요소를 공유하는 sister 클래스가 선택된다.

인접 형제 결합자

  • 첫 번째 요소의 바로 뒤에 위치하면서 같은 부모를 공유하는 두 번째 요소 선택

  • + 사용

.brother + .sister {
  color: red;
}

brother 클래스와 같은 부모를 공유하는 형제이고, brother 클래스 바로 뒤에 위치한 sister 클래스가 선택된다.

<html>
  <div class="brother">brother</div>
  <div class="other">other</div>
  <div class="sister">
    sister
  </div>
  <div class="brother">brother</div>
</html>

brother 클래스 바로 뒤에 other 클래스가 위치하고 있으므로, 아무도 선택되지 않는다.

<html>
  <div class="brother">brother</div>
  <div class="sister">
    sister
  </div>
  <div class="sister">
    sister
  </div>
  <div class="brother">brother</div>
</html>

brother 클래스 바로 뒤에 위치한 sister 클래스 1개만 선택된다.

💃 활용하기

<html>
  <div class="hover">Hover</div>
  <div class="target">Target</div>
</html>

다시 처음으로 돌아가서, hover 클래스가 hover 되었을 때 target 클래스의 폰트 색상을 변경하고 싶다면 어떻게 해야할까?!

.hover:hover ~ .target {
  color: red;
}

정답은 위와 같다!


728x90