[CSS] 의사클래스 - only-child, only-of-type, empty, empty, root


Study/Javascript, Jquery, CSS  2020. 1. 21. 23:22

안녕하세요. 명월입니다.


이 글은 CSS에서의 의사클래스(only-child, only-of-type, empty, empty, root)에 대한 글입니다.


이전에 의사클래스의 선택자를 설명한 적이 있습니다.

링크 - [CSS] 의사클래스 - nth-child, nth-of-type, nth-last-child, nth-last-of-type

링크 - [CSS] 의사클래스 - first-child, last-child, first-of-type, last-of-type


의사클래스 선택자는 태그(요소)의 위치에 따른 선택이 되는 것입니다만 이 글에서의 의사클래스는 유일한 요소인지, 존재하지 않는 지에 대한 선택자입니다.

<!DOCTYPE html>
<html>
  <head><title>css</title></head>
  <body>
    <!-- 첫번째 test 클래스 태그: test 클래스의 div 태그에 p 태그를 가지고 있다. -->
    <div class="test">
      <p>This is p tag.</p>
    </div>
    <br />
    <!-- 두번째 test 클래스 태그: test 클래스의 div 태그에 p 태그와 span태그를 두개 가지고 있다. -->
    <div class="test">
      <span>This is span tag.</span>
      <p>This is p tag.</p>
      <span>This is span tag.</span>
    </div>
    <br />
    <!-- 세번째 test 클래스 태그: test 클래스의 div 태그에 span태그를 가지고 있다. -->
    <div class="test">
      <p>This is p tag.</p>
      <span>This is span tag.</span>
      <p>This is p tag.</p>
    </div>
    <!-- 네번째 test 클래스 태그: test 클래스의 div 태그에 파생 요소가 없다. -->
    <div class="test"></div>
  </body>
</html>

/* test클래스의 p태그가 유일한 경우를 선택한다.*/
.test p:only-child {
  color:red;
}
/* test클래스의 span태그가 하나있는 경우를 선택한다.*/
.test span:only-of-type {
  color:blue;
}
/* test클래스에 파생 태그가 없는 경우를 선택한다.*/
.test:empty {
  height:10px;
  background-color:green;
}
/* html 태그를 지칭한다.*/
:root {
  background-color:pink;
}

위 예제를 보면 css 스타일은 총 네가지가 있습니다.

첫번째는 test클래스의 p태그가 유일한 경우입니다만, 첫번째 태그의 경우는 div 태그에 p태그가 하나가 있습니다. 두번째 태그의 경우는 p태그가 하나 있습니다만, span 태그가 있습니다. 유일한 태그가 아닙니다.

그러므로 첫번째 태그만 폰트 색이 빨간색으로 적용됩니다.

두번째는 span 태그가 하나만 있는 경우 입니다. 세번째 태그의 경우 유일한 태그는 아닙니다만, span태그는 한개가 있기 때문에 세번째 태그가 폰트 색이 파란 색으로 적용이 됩니다.

마지막으로 text클래스에서 파생 요소가 없는 경우는 마지막 네번째 태그입니다. 참고로 하위 파생 태그 뿐만 아니라, 텍스트 값도 있으면 empty가 적용이 되지 않습니다.

root는 가장 최상위 태그입니다. 최상위 태그는 html밖에 없으므로 :root는 html 태그의 고정입니다.

여기까지 CSS에서의 CSS에서의 의사클래스(only-child, only-of-type, empty, empty, root)에 관한 설명이었습니다.


궁금한 점이나 잘못된 점이 있으면 댓글 부탁드립니다.