CSS : Peusdo-Element Selector

?·2020년 8월 13일
0

What I've learned

목록 보기
2/21


위의 이미지는 내가 만든 자기소개 페이지의 상단 navigation bar이다. 디자인적 요소를 위해서 회색의 라인을 추가 했는데, 문제는 element 보다 짧은 border line 을 만들려고 하다보니 일반적인 border 속성으로는 구현이 어려웠다.

그래서 이것을 해결하기 위한 과정에서 가상요소 셀렉터를 알게되었다.

가상 요소 셀렉터 (Peusdo-Element Selector)

가상 요소는 요소의 특정 부분에 스타일을 적용하기 위하여 사용된다. 특정 부분이란 예를 들어 다음과 같다.

  • 요소 콘텐츠의 첫글자 또는 첫줄
  • 요소 콘텐츠의 앞 또는 뒤

가상 요소에는 두개의 콜론(::)을 사용한다. CSS 표준에 의해 미리 정의된 이름이 있기 때문에 임의의 이름을 사용할 수 없다.

selector::pseudo-element {
  property:value;
}

의 형태로 사용된다.

가상요소 셀렉터의 속성들로는 다음과 같은 것들이 있다.

  • ::first-letter : 콘텐츠의 첫글자를 선택한다.
  • ::first-line : 콘텐츠의 첫줄을 선택한다. 블록 요소에만 적용할 수 있다.
  • ::after : 콘텐츠의 뒤에 위치하는 공간을 선택한다. 일반적으로 content attribute와 함께 사용된다.
  • ::before : 콘텐츠의 앞에 위치하는 공간을 선택한다. 일반적으로 content attribute와 함께 사용된다.
  • ::selection : 드래그한 콘텐츠를 선택한다. iOS Safari 등 일부 브라우저에서 동작하지 않는다.
<!DOCTYPE html>
<html>
<head>
  <style>
    /* p 요소 콘텐츠의 첫글자를 선택 */
    p::first-letter { font-size: 3em; }
    /* p 요소 콘텐츠의 첫줄을 선택 */
    p::first-line   { color: red; }

    /* h1 요소 콘텐츠의 앞 공간에 content 어트리뷰트 값을 삽입한다 */
    h1::before {
      content: " HTML!!! ";
      color: blue;
    }
    /* h1 요소 콘텐츠의 뒷 공간에 content 어트리뷰트 값을 삽입한다 */
    h1::after {
      content: " CSS3!!!";
      color: red;
    }

    /* 드래그한 콘텐츠를 선택한다 */
    ::selection {
      color: red;
      background: yellow;
    }
  </style>
</head>

나는 이중 after를 이용하여 짧은 border line을 구현했다. 코드는 다음과 같다.
<html>
   <head>
     <style>
        #topline{
           content: "";
           height:0px;
           width:100%;
           position: absolute fixed;
        }

        #topline:after {
            content: "";
            display: block;
            margin: 0 auto;
            width: 85%;
            border-bottom: 3px solid darkgrey;
        }
     </style>
   </head>
   <body>
    <div class = "container">
      <header>
        <div id="topmenu">
            <a href="./intro_myself.html" title="Home">
            <h1 id="eunsonny"><span>Eunsonny</span></h1></a>
            <nav class= "nav">
              <a href="./part1.html" class="menu" title="click me">&#xe801</a>
              <a href="./part2.html" class="menu" title="click me">&#xe803</a>
              <a href="./part3.html" class="menu" title="click me">&#xe806</a>
            </nav>
        </div>
        <div id="topline"> </div>
      </header>
    </body>
  </html>
profile
?

0개의 댓글