본문 바로가기
study/CSS

선택자 04 - 의사요소 선택자, 구조 선택자, 부정선택자, child, nth-chid, not

by Elfen Lied 2020. 1. 24.
반응형

*의사요소 선택자

<!-- before -->

h1:before{
          content:'before ';
          color:red;
          }

<h1 id="title">css 기본 문법</h1>


<!-- after -->

h1:after{
          content:'after ';
          color:blue;
          }

<h1 id="title">css 기본 문법</h1>

- before 에 content 를 해주면 BEFORE css기본 문법 앞쪽에 들어간다.

- after에 content 를 해주면 css기본 문법 AFTER 뒤쪽에 들어간다.

 

그리고 css에서 만들었기 때문에 html상에 없고 가상으로 만든거기 때문에 드래그나 선택불가.

 

<!-- before -->

h1:before{
          content:'';
          display: inline-block;
          width:15px;
          height:15px;
          margin-right:20px;
          background-color:red;
          }

<h1 id="title">css 기본 문법</h1>


<!-- after -->

h1:after{
          content:'after ';
          color:blue;
          }

<h1 id="title">css 기본 문법</h1>

이런식의 다양한 형태로 가능하다.

 

*구조 선택자

- 첫번째 자식과 마지막 자식 지정

li:first-child{
        text-decoration:underline;
        }

li:last-child{
        text-decoration:underline;
        }

<ul>
  <li>첫번째 자식</li>
  <li>리스트 아이템</li>
  <li>리스트 아이템</li>
  <li>리스트 아이템</li>
  <li>리스트 아이템</li>
  <li>마지막 자식</li>
</ul>

li:first-child, li:last-child 로 쓴다.

 

 

- 지정 번째 자식 선택

li:nth-child(3){
		text-decoration:underline;
		}
<ul>
  <li>리스트 아이템</li>
  <li>리스트 아이템</li>
  <li>세번째 자식</li>
  <li>리스트 아이템</li>
  <li>리스트 아이템</li>
  <li>리스트 아이템</li>
</ul>

li:nth-child(번호) {text-decoration: underline;} 번호 부분에 선택할 자식 위치번호를 쓴다.

 

- 짝수번들과 홀수번들 자식 선택

 

짝수

li:nth-child(2n){
		text-decoration:underline;
		}
<ul>
  <li>리스트 아이템</li>
  <li>(짝수)2배수 자식들</li>
  <li>리스트 아이템</li>
  <li>(짝수)2배수 자식들</li>
  <li>리스트 아이템</li>
  <li>(짝수)2배수 자식들</li>
</ul>

 

홀수

li:nth-child(2n+1){
		text-decoration:underline;
		}

 

여기선 n은 0부터 시작해서 1씩 곱한다.

ex) 2 * n(0) + 1 = 1번째

     2 * n(1) + 1 = 3번째

     2 * n(2) + 1 = 5번째 

 

 

첫번째에서 세번째까지만 하고싶다면

li:nth-child(-n+3){
		text-decoration:underline;
		}

ex) -n(0) + 3 = 3번째

     -n(1) + 3 = 2번째

     -n(2) + 3 = 1번째 

 

 

네번째이상 부터 하고싶다면

li:nth-child(n+4){
		text-decoration:underline;
		}

 

 

 

- 선택 외에 모든것 선택할시

 

:not(제외할것) {스타일}

h1 {color:#000;}
:not(h1){
        color:red;
        }


<h1 id="title">css 기본 문법</h1>
<h2>의사요소 선택자(psedo element selector)</h2>
<ul>
  <li>리스트 아이템</li>
  <li>리스트 아이템</li>
  <li>리스트 아이템</li>
  <li>리스트 아이템</li>
  <li>리스트 아이템</li>
  <li>리스트 아이템</li>
</ul>
<h3>heading 3</h3>
<h4>heading 4</h4>
<h3>heading 3</h3>
<h3>heading 3</h3>
<h4>heading 4</h4>

 

 

h1 이외에 나머지를 바꿀때

:not(h1) { color:red;}

반응형

댓글