여러분이 사용하고 계신 브라우저는 HTML5를 지원하지 않기 때문에 몇몇 요소가 제대로 보이도록 JScript를 사용하고 있습니다. 하지만 여러분의 브라우저 설정에서 스크립트 기능이 꺼져있으므로, 현재 페이지를 제대로 확인하시려면 스크립트 기능을 켜주셔야 합니다. CSS - 기초 - 결합자
CSS – 기초 – 결합자
2년전 작성
2년전 수정

결합자

결합자 = combinators. 결합자는 두 가지의 선택자를 입력하여 조금 더 명확하게 선택자를 선택할 수 있다.

결합자
하위 결합자
:
article p. article 요소의 하위 요소인 p 요소들이 모두 적용된다.
자식 결합자
:
article > p. article 요소의 바로 하위 요소인 p 요소에만 적용된다.
인접 형제 결합자
:
h1 + p. li:first-of-type + li. 두 선택자를 분리했을 때 동일한 부모 선택자의 자식으로 첫번째 선택자의 바로 뒤에 오는 선택자가 두번째 선택자인경우 이 결합자가 적용된다.
일반 형제 결합자
:
h1 ~ p. 두 선택자를 분리했을 때 동일한 부모 요소의 자식으로 첫번째 선택자의 뒤에 두번째 선택자가 있는경우 적용된다. 이 때 무조건 바로 뒤에 있지 않아도 적용된다.

하위 결합자

상위 요소의 하위 요소 중 기재해놓은 요소가 맞다면 모두 적용된다.

아래 예시에서, li의 하위 요소 li 선택하여 적용.

기본 예시
  • Item 1
    • Subitem A
    • Subitem B
  • Item 2
    • Subitem A
    • Subitem B

 

CSS
ul.my-things li {
  margin: 2em;
  list-style-type: disc;
}

li li {
  list-style-type: circle;
}
HTML
<ul class="my-things">
  <li>
    <div>Item 1</div>
    <ul>
      <li>Subitem A</li>
      <li>Subitem B</li>
    </ul>
  </li>
  <li>
    <div>Item 2</div>
    <ul>
      <li>Subitem A</li>
      <li>Subitem B</li>
    </ul>
  </li>
</ul>

자식 결합자

상위 요소에 포함되는 하위 요소 중 입력된 요소에만 적용된다.

아래 예시에서, div의 하위 span만 선택하여 적용.

기본 예시

Span #1, in the div.Span #2, in the span that’s in the div.

Span #3, not in the div at all.

 

CSS
span {
  background-color: aqua;
}

div > span {
  background-color: yellow;
}
HTML
<div>
  <span>Span #1, in the div.
    <span>Span #2, in the span that's in the div.</span>
  </span>
</div>
<span>Span #3, not in the div at all.</span>

인접 형제 결합자

+ 를 이용하여 먼저 입력한 요소의 바로 다음 형제 요소를 선택한다.

아래 예시에서, 첫번째 li의 인접 형제 li 선택하여 적용.

기본 예시
  • One
  • Two!
  • Three

 

CSS
li:first-of-type + li {
  color: red;
}
HTML
<ul>
  <li>One</li>
  <li>Two!</li>
  <li>Three</li>
</ul>

일반 형제 결합자

~ 을 이용하여 먼저 입력한 요소의 다음 요소 중 입력한 요소를 선택한다.

아래 예시에서,

기본 예시
This is not red.

Here is a paragraph.

Here is some code.
And here is a red span!
And this is a red span!
More code...

How are you?

Whatever it may be, keep smiling.

Dream big
And yet again this is a red span!

 

CSS
p ~ span {
  color: red;
}
HTML
<span>This is not red.</span>
<p>Here is a paragraph.</p>
<code>Here is some code.</code>
<span>And here is a red span!</span>
<span>And this is a red span!</span>
<code>More code...</code>
<div> How are you? </div>
<p> Whatever it may be, keep smiling. </p>
<h1> Dream big </h1>
<span>And yet again this is a red span!</span>
참고
관련 포스트
CSS - 기초 - 결합자 - 현재글

Mingg`s Diary
밍구
공부 목적 블로그