CSS3 - Selector

이소라·2021년 6월 14일
0

selector

  • style을 적용하고자 하는 HTML 요소를 특정하는 역할
  • HTML 요소를 여러 개 선택할 수 있으며, 쉽표(,)로 구분함
h1, p {color: red; }

1. Universal Selector

  • *로 표시함
  • HTML 문서 내 모든 요소 (head 요소 포함)를 선택함
<!DOCTYPE html>
<html>
  <head>
    <style>
      * {color: red; }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <div>
      <p>Paragraph1</p>
      <p>Paragraph2</p>
    </div>
    <p>Paragraph3</p>
  </body>
</html>

2. Tag Selector

  • 지정한 태그명을 가지는 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      p {color: red; }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <div>
      <p>Paragraph1</p>
      <p>Paragraph2</p>
    </div>
    <p>Paragraph3</p>
  </body>
</html>

3. ID Selector

  • #id attribute 값으로 표시
  • id attribute 값을 지정하여 일치하는 요소를 선택
  • id attribute 값은 중복될 수 없음
<!DOCTYPE html>
<html>
  <head>
    <style>
      #p1 {color: red; }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <div class="container">
      <p id="p1">Paragraph1</p>
      <p id="p2">Paragraph2</p>
    </div>
    <p>Paragraph3</p>
  </body>
</html>

Class Selector

  • .class attribute 값으로 표시
  • class attribute 값을 지정하여 일치하는 요소를 선택
  • class attribute 값은 중복 가능
<!DOCTYPE html>
<html>
  <head>
    <style>
      .container {color: red; }
      #p2 {color: initial; }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <div class="container">
      <p id="p1">Paragraph1</p>
      <p id="p2">Paragraph2</p>
    </div>
    <p>Paragraph3</p>
  </body>
</html>

  • HTML 요소에 class attribute 값을 공백으로 구분하여 여러 개 지정 가능
  • HTML 요소에 이미 지정되어 있는 class를 지정하여 필요한 style을 지정 가능
<!DOCTYPE html>
<html>
  <head>
    .text-center { text-align: center; }
    .text-large { font-size: 200%; }
    .text-red { color: red; }
    .text-blue { color: blue; }
  </head>
  <body>
    <p class="text-center">Center</p>
    <p class="text-large text-red">Large Red</p>
    <p class="text-center text-large text-blue">Center Large Blue</p>
  </body>
</html>

5. Attribute Selector

selector[attribute]

  • 지정된 attribute를 갖는 모든 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      a[href] { color : red; }
    </style>
  </head>
  <body>
    <a href="http://www.poiemaweb.com">poiemaweb.com</a>
    <a href="http://www.google.com" target="_blank">google.com</a>
    <a href="http://www.naver.com" target="_top">naver.com</a>
  </body>
</html>

selector[attribute="값"]

  • 지정된 attribute를 갖고 있으며, 그 attribute 값이 지정된 값과 일치하는 모든 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      a[target="_blank"] { color : red; }
    </style>
  </head>
  <body>
    <a href="http://www.poiemaweb.com">poiemaweb.com</a>
    <a href="http://www.google.com" target="_blank">google.com</a>
    <a href="http://www.naver.com" target="_top">naver.com</a>
  </body>
</html>

selector[attribute~="값"]

  • 지정된 attribute를 갖고 있으며, 그 값이 지정된 값을 (공백으로 분리된) 단어로 포함하고 있는 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      h1[title~="first"] { color: red; }
    </style>
  </head>
  <body>
    <h1 title="heading first">Heading first</h1>
    <h1 title="heading-first">Heading-first</h1>
    <h1 title="heading second">Heading second</h1>
    <h1 title="heading third">Heading third</h1>
  </body>
</html>

selector[attribute|="값"]

  • 지정된 attribute 값과 일치하거나, 지정된 attribute 값 뒤 - 로 시작하는 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      p[style|="en"] { color: red; }
    </style>
  </head>
  <body>
    <p lang="en">Hello</p>
    <p lang="en-us">Hi</p>
    <p lang="en-gb">Ello</p>
    <p lang="us">Hi</p>
    <p lang="no">Hei</p>
  </body>
</html>

selector[attribute^="값"]

  • 지정된 attribute 값으로 시작하는 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      a[href^="https://"] { color: red; }
    </style>
  </head>
  <body>
    <a href="https://www.test.com">https://www.test.com</a><br>
    <a href="http://www.test.com">http://www.test.com</a>
  </body>
</html>

selector[attribute$="값"]

  • 지정된 attribute 값으로 끝나는 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      a[href$="html"] { color: red; }
    </style>
  </head>
  <body>
    <a href="test.html">test.html</a><br>
    <a href="test.jsp">test.jsp</a>
  </body>
</html>

selector[attribute*="값"]

  • 지정된 attribute 값을 포함하는 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      /*div 요소 중 class attribute 값에 "test"를 포함하는 요소*/
      div[class*="test"] { color: red; }
      /*div 요소 중 class attribute 값에 "test"를 단어로 포함하는 요소*/
      div[class~="test"] { background-color: red; }
    </style>
  </head>
  <body>
    <div class="first-test">The first div element</div>
    <div class="second">The second div element</div>
    <div class="test">The third div element</div>
    <p class="test">This is some text </p>
  </body>
</html>

6. Combinator

combinator

  • parent 요소 : 자신보다 1 level 상위에 속하는 요소
  • child 요소 : 자신보다 1 level 하위에 속하는 요소
  • desendant 요소 : 자신보다 n level 하위에 속하는 요소

6.1 Desendant Combinator

selector_A selector_B
  • selector_A의 모든 desendant 요소 중 selector_B와 일치하는 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      div p { color: red; }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <div>
      <p>paragraph 1</p>
      <p>paragraph 2</p>
      <span><p>paragraph 3</p></span>
    </div>
    <p>paragraph 4</p>
  </body>
</html>

6.2 Child Combinator

selector_A > selector_B
  • selector_A의 모든 child 요소 중 select_B와 일치하는 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      div > p { color: red; }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <div>
      <p>paragraph 1</p>
      <p>paragraph 2</p>
      <span><p>paragraph 3</p></span>
    </div>
    <p>paragraph 4</p>
  </body>
</html>

6.3 Sibling Combinator

sibling combinator

  • 동위 관계에서 뒤에 위치하는 요소를 선택

6.3.1 Adjacent Sibling Combinator

selector_A + selector_B
  • selctor_A의 sibling 요소 중 selector_A 바로 뒤에 있는 selector_B 요소를 선택
  • A와 B 사이에 다른 요소가 존재하면 선택 X
<!DOCTYPE html>
<html>
  <head>
    <style>
      p + ul { color: red; }
    </style>
  </head>
  <body>
    <div>A div element</div>
    <ul>
      <li>Coffee</li>
      <li>Tea</li>
      <li>Milk</li>
    </ul>
    
    <p>The first paragraph</p>
    <ul>
      <li>Coffee</li>
      <li>Tea</li>
      <li>Milk</li>
    </ul>
    
    <h2>Another list</h2>
    <ul>
      <li>Coffee</li>
      <li>Tea</li>
      <li>Milk</li>
    </ul>
  </body>
</html>

6.3.2 General Sibling Combinator

selector_A ~ selector_B
  • selector_A의 sibling 요소 중 selector_A 뒤에 위치하는 selector_B 요소를 모두 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      p ~ ul { color: red; }
    </style>
  </head>
  <body>
    <div>A div element</div>
    <ul>
      <li>Coffee</li>
      <li>Tea</li>
      <li>Milk</li>
    </ul>
    
    <p>The first paragraph</p>
    <ul>
      <li>Coffee</li>
      <li>Tea</li>
      <li>Milk</li>
    </ul>
    
    <h2>Another list</h2>
    <ul>
      <li>Coffee</li>
      <li>Tea</li>
      <li>Milk</li>
    </ul>
  </body>
</html>

7. Pseudo-Class Selector

selctor:pseudo-class {
	property: value;
}
  • 가상 클래스는 요소의 특정 상태에 따라 스타일을 정의할 때 사용
    • 특정상태 : 마우스가 올라와 있을 때,
      링크를 방문했을 때와 아직 방문하지 않았을 때, 포커스가 들어와 있을 때
  • 이러한 특정상태에는 원래 클래스가 존재하지 않지만, 가상 클래스를 임의로 지정하여 선택
  • 가상 클래스는 마침표(.) 대신 콜론(:)을 사용
  • CSS 표준에 미리 정의된 이름 존재 (임의로 지정 불가)
<!DOCTYPE html>
<html>
  <head>
    <style>
      /* a 요소가 hover(마우스에 올라와 있을 때) 상태일 때*/
      a:hover { color: red; }
      /*input 요소가 focus 상태일 때*/
      input:focus { background-color: yellow; }
    </style>
  </head>
  <body>
    <a href="#">Hover me</a><br><br>
    <input type="text" placehorder="focus me">
  </body>
</html>

pseudo-classdescription
:linkselector가 방문하지 않은 링크일 때
:visitedseletor가 방문한 링크일 때
:hoverselector에 마우스가 올라와 있을 때
:activeselector가 클릭된 상태일 때
<!DOCTYPE html>
<html>
  <head>
    <style>
      /* a 요소가 방문하지 않은 링크일 때*/
      a:link { color: orange; }
      
      /* a 요소가 방문한 링크일 때*/
      a:visited { color: green; }
      
      /* a 요소에 마우스가 올라와 있을 때*/
      a:hover { font-weight: bold; }
      
      /* a 요소가 클릭된 상태일 때*/
      a:active { color: blue; }
      
      /* text와 password input 요소에 포커스가 들어와 있을 때*/
      input[type=text]:focus,
      input[type=password]:focus { color: red; }
    </style>
  </head>
  <body>
    <a href="#" target="_blank">This is a link</a><br>
    <input type="text" value="I'll be red when focused"><br>
    <input type="password" value="I'll be red when focused">
  </body>
</html>

7.2 UI element states pseudo-classes

pseudo-classdescription
:checkedselector가 체크 상태일 때
:enabledselector가 사용 가능한 상태일 때
:disabledselector가 사용 불가능한 상태일 때
<!DOCTYPE html>
<html>
  <head>
    <style>
      /* input 요소가 사용 가능한 상태일 때,
      input 요소 바로 뒤에 위치하는 인접 형제 span 요소를 선택*/
      input:enabled + span {
      	color: blue;
      }
      
      /* input 요소가 사용 불가능한 상태일 때,
      input 요소 바로 뒤에 위치하는 인접 형제 span 요소를 선택*/
      input:disabled + span {
      	color: gray;
      	text-decoration: line-through;
      }
      
      /* input 요소가 체크 상태일 때,
      input 요소 바로 뒤에 위치하는 인접 형제 span 요소를 선택*/
      input:checked + span {
      	color: red;
      }
    </style>
  </head>
  <body>
    <input type="radio" checked="checked" value="male" name="gender"><span>Male</span><br>
    <input type="radio" value="female" name="gender"><span>Female</span><br>
    <input type="radio" value="neuter" name="gender" disabled><span>Male</span><hr>
    
    <input type="checkbox" checked="checked" value="bicycle"><span>I have a bicycle</span><br>
    <input type="checkbox" value="car"><span>I have a car</span><br>
    <input type="checkbox" value="motocycle" disabled><span>I have a motocycle</span>
  </body>
</html>

7.3 Structural pseudo-classes

pseudo-classdescription
:first-childselector에 해당하는 모든 요소 중 첫번째 자식인 요소를 선택
:last-childselector에 해당하는 모든 요소 중 마지막 자식인 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      /* p 요소 중 첫번째 자식 요소 선택*/
      p:first-child { color: red;}
      /* p 요소 중 마지막 자식 요소 선택
      body 요소의 마지막 자식 요소는 두번째 p 요소가 아닌 div 요소임*/
      p:last-child { color: blue;}
    </style>
  </head>
  <body>
    <p>This paragraph is the first child of its parent(body)</p>
    
    <h1>Welcome to my Homepage</h1>
    <p>This paragraph is not the first child of its parent</p>
    
    <div>
      <p>This paragraph is the first child of its parent(div)</p>
      <p>This paragraph is not the first child of its parent</p>
    </div>
  </body>
</html>

pseudo-classdescription
:nth-child(n)selector에 해당하는 모든 요소 중 앞에서 n번째 자식인 요소 선택
:nth-last-child(n)selector에 해당하는 모든 요소 중 뒤에서 n번째 자식인 요소 선택
  • n : 0부터 시작하는 정수
<!DOCTYPE html>
<html>
  <head>
    <style>
      /* ol 요소의 자식 요소인 li 요소 중에서 짝수번째 요소만 선택 */
      ol> li:nth-child(2n) { color: orange; }
      /* ol 요소의 자식 요소인 li 요소 중에서 홀수번째 요소만 선택 */
      ol> li:nth-child(2n+1) { color: green; }
      
      /* ol 요소의 자식 요소인 li 요소 중에서 첫번째 요소만 선택 */
      ol> li:first-child { color: red; }
      /* ol 요소의 자식 요소인 li 요소 중에서 마지막 요소만 선택 */
      ol> li:last-child { color: blue; }
      
      /* ol 요소의 자식 요소인 li 요소 중에서 4번째 요소만 선택 */
      ol> li:nth-child(4) { background: brown; }
      
      /* ul의 자식 요소인 li 요소 중에서 뒤에서부터 시작해서 홀수번째 요소만 선택*/
      ul> li:nth-last-child(2n+1) { color: red; }
      /* ul의 자식 요소인 li 요소 중에서 뒤에서부터 시작해서 짝수번째 요소만 선택*/
      ul> li:nth-last-child(2n) { color: blue; }
    </style>
  </head>
  <body>
    <ol>
      <li>Espresso</li>
      <li>Americano</li>
      <li>Caffe Latte</li>
      <li>Caffe Mocha</li>
      <li>Caramel Latte</li>
      <li>Cappuccino</li>
    </ol>
    <ul>
      <li>Espresso</li>
      <li>Americano</li>
      <li>Caffe Latte</li>
      <li>Caffe Mocha</li>
      <li>Caramel Latte</li>
      <li>Cappuccino</li>
    </ul>
  </body>
</html>

pseudo-classdescription
:first-of-typeselector에 해당하는 요소의 부모 요소의 자식 요소 중 첫 번째로 등장하는 요소를 선택
:last-of-typeselector에 해당하는 요소의 부모 요소의 자식 요소 중 마지막으로 등장하는 요소를 선택
:nth-of-type(n)selector에 해당하는 요소의 부모 요소의 자식 요소 중 앞에서 n번째에 등장하는 요소를 선택
:nth-last-of-type(n)selector에 해당하는 요소의 부모 요소의 자식 요소 중 뒤에서 n번째에 등장하는 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      /* p 요소의 부모 요소의 자식 요소 중 첫번째로 등장하는 p 요소 */
      p:first-of-type { color: red; }
      /* p 요소의 부모 요소의 자식 요소 중 마지막으로 등장하는 p 요소 */
      p:last-of-type { color: blue; }
      /* p 요소의 부모 요소의 자식 요소 중 앞에서 2번째에 등장하는 p 요소 */
      p:nth-of-type(2) { color: green; }
      /* p 요소의 부모 요소의 자식 요소 중에서 뒤에서 2번째에 등장하는 p 요소*/
      p:nth-last-of-type(2) { color: orange; }
      /* p 요소 중에서 첫번째 자식 요소를 선택 */
      p:first-child { background: brown; }
    </style>
  </head>
  <body>
    <h1>This is a heading</h1>
    <p>The first paragraph</p>
    <p>The second paragraph</p>
    <p>The third paragraph</p>
    <p>The fourth paragraph</p>
    <div>
      <h1>This is a heading</h1>
      <p>The first paragraph</p>
      <p>The second paragraph</p>
      <p>The third paragraph</p>
      <p>The fourth paragraph</p>
    </div>
  </body>
</html>

7.4 Negation pseudo-classes

pseudo-classdescription
:not(selector)selector에 해당하지 않는 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      /* input 요소 중에서 type attribute 값이 password가 아닌 요소를 선택*/
      input:not([type=password]) {
      	background : yellow;
      }
    </style>
  </head>
  <body>
    <input type="text" value="text input">
    <input type="email" value="email input">
    <input type="password" value="password input">
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
      margin: 0;
    }
      div {
      float: left;
      width: 32%;
      height: 200px;
      background-color: red;
      color: #fff;
      font-size: 3em;
      line-height: 200px;
      text-align: center;
    }
      /* div 요소 중 1, 4, 7... 번째 등장하는 요소가 아닌 요소만을 선택*/
      div:not(:nth-of-type(3n+1)) {
      	margin-left: 2%;
      }
      /* div 요소 중 4번째 이후에 등장하는 요소가 아닌 요소만을 선택*/
      div:not(:nth-of-type(n+4)) {
      	margin-bottom: 2%;
      }
    </style>
  </head>
  <body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
  </body>
</html>

7.5 Validity pseudo-classes

pseudo-classdescription
:validvalidity 검증에 성공한 input 또는 form 요소를 선택
:invalidvalidity 검증에 실패한 input 또는 form 요소를 선택
<!DOCTYPE html>
<html>
  <head>
    <style>
      input[type=text]:valid {
      	background-color: greenyellow;
      }
      input[type=text]:invalid {
      	background-color: red;
      }
    </style>
  </head>
  <body>
    <label>입력값이 반드시 필요
      <input type="text" required>
    </label>
    <br>
    <label>특수문자를 포함하지 않는 4자리 문자 또는 숫자
      <input type="text" value="ab1!"
             pattern="[a-zA-Z0-9]{4}" required>
    </label>
    <br>
    <label>핸드폰 번호 형식
      <input type="text" value="010-1111-2222" 
             pattern="^\d{3}-\d{3,4}-\d{4}$" required>
    </label>
  </body>
</html>

8. Pseudo-Element Selector

selector::pseudo-element {
	property: value;
}
  • 가상 요소는 요소의 특정 부분에 스타일을 적용하기 위해 사용
    • 요소 컨텐츠의 첫글자 또는 첫줄
    • 요소 컨텐츠의 앞 또는 뒤
  • 가상 요소에는 두 개의 콜론(::)을 사용
  • CSS표준에 의해 미리 정의된 이름이 있음 (임의의 이름 사용 불가능)

pseudo-classdescription
::first-letter요소 컨텐츠의 첫글자를 선택
::first-line요소 컨텐츠의 첫줄을 선택, 블럭 요소에만 적용 가능
::after요소 컨텐츠의 뒤에 위치한 공간을 선택, 일반적으로 content property와 함께 사용
::before요소 컨텐츠의 앞에 위치한 공간을 선택, 일반적으로 content property와 함께 사용
::selection드래그한 컨텐츠를 선택, IOS Safari 등 일부 브라우저에 동작 X
<!DOCTYPE html>
<html>
  <head>
    <style>
      /* p 요소 컨텐츠의 첫글자 선택*/
      p::first-letter { font-size: 3em; }
      /* p 요소 컨텐츠의 첫줄 선택*/
      p::first-line { color: red; }
      
      /* h1 요소 컨텐츠의 앞 공간에 content attribute값을 삽입*/
      h1::before {
      	content: "HTML!!!";
      	color: blue;
      }
      /* h1 요소 컨텐츠의 뒤 공간에 content attribute값을 삽입*/
      h1::after {
      	content: "CSS!!!";
      	color: red;
      }
      
      /* 드래그한 컨텐츠를 선택*/
      ::selection {
      	color: red;
      	background: yellow;
      }
    </style>
  </head>
  <body>
    <h1>This is a heading</h1>
    <p>Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language such as HTML. CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript.</p>
  </body>
</html>

0개의 댓글