셀렉터 (Selector)

맹뿌·2021년 5월 27일
0

CSS3

목록 보기
2/10

① 전체 셀렉터 (Universal Selector)

<head>
  <style>
    * { color: red; } // * → 모든 요소를 선택
  </style>
</head>

② 태그 셀렉터 (Type Selector)

<head>
  <style>
    p { color: red; } // 모든 p 태그 요소를 선택
  </style>
</head>

③ ID 셀렉터 (ID Selector)

id 속성값은 중복이 불가능함.

<!DOCTYPE html>
<html>
  <head>
    <style>
      #p1 { color: red; } // id 값이 p1인 요소를 선택
    </style>
  </head>
<body>
  <h1>Heading</h1>
  <div class="container">
    <p id="p1">paragraph 1</p>
    <p id="p2">paragraph 2</p>
  </div>
  <p>paragraph 3</p>
</body>
</html>

④ 클래스 셀렉터 (Class Selector)

클래스 속성값은 중복이 가능함.

<head>
  <style>
    .container { color: red; } // container 클래스의 모든 요소를 선택
    #p2 { color: initial; }
    // 클래스 셀렉터로 지정하여 p2의 색깔도 빨강이 되어야 하지만 p2의 경우, id 셀렉터로 따로 지정.
  </style>
</head>
<body>
  <h1>Heading</h1>
  <div class="container">
    <p id="p1">paragraph 1</p>
    <p id="p2">paragraph 2</p>
  </div>
</body>
  • 클래스 셀렉터를 사용해야 할까요, ID 셀렉터를 사용해야 할까요?
    클래스 속성값은 중복이 가능하기 때문에 한 페이지 내에서 여러 번 반복될 필요가 있는 스타일은 클래스 선택자를 사용하는 것이 좋다.

⑤ 속성 셀렉터 (Attribute Selector)

  • E[attr] : 'attr' 속성이 포함된 요소 E를 선택
  • E[attr="val"] : 'attr' 속성의 값이 정확하게 'val'과 일치하는 요소 E를 선택
  • E[attr~="val"] : 'attr' 속성의 값에 'val'이 포함되는 요소를 선택 (공백으로 분리된 값이 일치해야-)
  • E[attr^="val"] : 'attr' 속성의 값이 'val'으로 시작하는 요소를 선택
  • E[attr$="val"] : 'attr' 속성의 값이 'val'으로 끝나는 요소를 선택
  • E[attr*="val"] : 'attr' 속성의 값에 'val'이 포함되는 요소를 선택
  • E[attr|="val"] : 'attr' 속성의 값이 정확하게 'val'이거나, 'val'으로 시작되는 요소를 선택
<head>
  <style>
    a[href] { color: red; } // a 요소 중에 href 속성을 갖는 모든 요소를 선택.
  </style>
</head>

사용 예제 1)

<head>
  <style>
    div[class*="test"] { color: red; }
    div[class~="test"] { background-color: yellow; }
  </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 in a paragraph.</p>
</body>

사용 예제 2)

<head>
  <style>
    p[lang|="en"] { color: red; }
  </style>
</head>

⑥ 복합 셀렉터 (Combinator)

1. 후손 셀렉터 (Descendant Combination)

  • 후손 요소 (하위 요소) : 부모 요소에 포함된 모든 하위 요소
<head>
  <style>
    div p { color: red; } // 패턴 : 셀렉터A 셀렉터B (ex. div p)
  </style>
</head>

2. 자식 셀렉터 (Child Combinator)

  • 자식 요소 (자손 요소) : 부모의 바로 아래의 요소
<head>
  <style>
    div > p { color: red; }
  </style>
</head>
<body>
  <h1>Heading</h1>
  <div>
    <p>paragraph 1</p> // red 적용
    <p>paragraph 2</p> // red 적용
    <span><p>paragraph 3</p></span> // div 아래 span 아래 p가 있기 때문에 style 적용 불가
  </div>
  <p>paragraph 4</p>
</body>

3. 형제(동위) 셀렉터 (Sibling Combinator)

3-1. 인접 형제 셀렉터 (Adjacent Sibling Combinator)

셀렉터A의 형제 요소 중 셀렉터A 바로 뒤에 위치하는 셀렉터B 요소를 선택한다.
A와 B 사이에 다른 요소가 존재하면 선택되지 않는다.

<head>
  <style>
  // p 요소의 형제 요소 중에 바로 뒤에 위치하는 ul 요소를 선택.
    p + ul { color: red; } // 패턴 : 셀렉터A + 셀렉터B
  </style>
</head>

3-2. 일반 형제 셀렉터 (General Sibling Combinator)

셀렉터A의 형제 요소 중 셀렉터A 뒤에 위치하는 셀렉터B 요소를 모두 선택한다.

<head>
  <style>
  // p 요소의 형제 요소 중, p 요소 뒤에 위치하는 ul 요소를 모두 선택.
    p ~ ul { color: red; } // 패턴 : 셀렉터A ~ 셀렉터B
  </style>
</head>

⑦ 가상 클래스 셀렉터🔥 (Pseudo-Class Selector)

셀렉터란 태그,id, class 등과 같이 HTML 문서에 존재하는 것들을 지정하는 것이다. 반면에 가상 클래스 선택자는 어떤 상태를 지정한다. 이런 상태는 태그, id, class처럼 HTML 문서 상에 있는 것이 아니다. 따라서 가상 셀렉터라고 한다.

예를 들면, 상태를 지정하는 가상 셀렉터에는 마우스를 올려 놓은 상태를 의미하는 hover 셀렉터, 방문하지 않은 링크를 나타내는 link 셀렉터, 이미 방문했던 링크를 나타내는 visited 셀렉터 등이 있다.

가상 클래스는 마침표(.) 대신에 콜론(:)을 사용한다.

selector:pseudo-class { property: value; } // 패턴

  • :link → 방문하지 않은 링크를 선택
  • :visited → 방문한 링크를 선택
  • :hover → 요소에 마우스가 올라와 있을 때 선택
  • :active → 해당 요소가 클릭된 상태일 때 선택
  • :focus → 포커스가 들어와 있을 때 선택
<!DOCTYPE html>
<html>
<head>
  <style>
    a:link { color: orange; }
    a:visited { color: green; }
    a:hover { font-weight: bold; }
    a:active { color: blue; }
    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>

2. UI 요소 상태 셀렉터 (UI element states pseudo-classes)

  • :checked : 셀렉터가 체크 상태일 때
  • :enabled : 셀렉터가 사용 가능한 상태일 때
  • :disabled : 셀렉터가 사용 불가능한 상태일 때
<head>
  <style>
    input:enabled + span {
      color: blue;
    } // input이 사용 가능일 때 뒤에 오는 span 요소에 적용.
    
    input:disabled + span {
      color: gray;
      text-decoration: line-through;
    } // input 요소가 사용 불가능일 때 뒤에 오는 span 요소에 적용.
    
    input:checked + span {
      color: red;
    } // input 요소가 체크 상태일 때 뒤에 오는 span 요소에 적용.
  </style>
</head>

3. 구조 가상 클래스 셀렉터 (Structural pseudo-classes)

  • :first-child : 자식들 중, 해당 요소가 첫번째로 등장하는 요소라면 선택
  • :last-child : 자식들 중, 해당 요소가 마지막으로 등장하는 요소라면 선택
  • :nth-child(n) : 자식들 중, 해당 요소가 앞에서부터 n번째 위치하는 요소라면 선택
  • :nth-last-child(n) : 자식들 중, 해당 요소가 뒤에서부터 n번째 위치하는 요소라면 선택
  • :first-of-type (3번째 예제 확인)
  • :last-of-type (3번째 예제 확인)
  • :nth-of-type(n) (3번째 예제 확인)
  • :nth-last-of-type(n) (3번째 예제 확인)

사용 예제 1)

<head>
  <style>
    p:first-child { color: red; }
    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>

사용 예제 2)

<head>
  <style>
    ol > li:nth-child(2n)   { color: orange; }
    ol > li:nth-child(2n+1) { color: green; }

    ol > li:first-child     { color: red; }
    ol > li:last-child      { color: blue; }

    ol > li:nth-child(4)    { background: brown; }

    ul > :nth-last-child(2n+1) { color: red; }
    ul > :nth-last-child(2n)   { color: blue; }
  </style>
</head>

사용 예제 3)

<!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>

4. 부정 셀렉터 (Negation pseudo-class)

  • :not : 셀렉터에 해당하지 않는 요소를 선택.
<head>
  <style>
    input:not([type=password]) {
      background: yellow;
    }
  </style>
</head>
<body>
  <input type="text" value="Text input"> // background 노랑
  <input type="email" value="email input"> // background 노랑
  <input type="password" value="Password input">
</body>

5. 정합성 체크 셀렉터 (Validity pseudo-class)

  • :valid(셀렉터) : 정합성 검증이 성공한 input 요소 또는 form 요소를 선택.
  • :invalid(셀렉터) : 정합성 검증이 실패한 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> // 입력값이 반드시 필요하지만 초기값이 설정되어 있지 않으므로 red.
  <br>
  <label>특수문자를 포함하지 않는 4자리 문자 또는 숫자
    <input type="text" value="ab1!"
      pattern="[a-zA-Z0-9]{4}" required>
  </label> // 특수문자를 포함하지 않아야 하지만 초기값이 특수문자를 포함하므로 red.
  <br>
  <label>핸드폰 번호 형식
    <input type="text" value="010-1111-2222"
      pattern="^\d{3}-\d{3,4}-\d{4}$" required>
  </label> // 번호 패턴과 초기값이 적합하므로 greenyellow.
</body>
</html>

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

  • ::first-letter : 콘텐츠의 첫글자를 선택.
  • ::first-line : 콘텐츠의 첫줄을 선택. 블록 요소에만 적용 가능.
  • ::after : 콘텐츠의 뒤에 위치하는 공간을 선택.
  • ::before : 콘텐츠의 앞에 위치하는 공간을 선택.
  • ::selection : 드래그한 콘텐츠를 선택.
<head>
  <style>
    h1::before {
      content: " HTML!!! ";
      color: blue;
    } // h1 요소 콘텐츠의 앞 공간에 content 속성 값을 삽입.

    h1::after {
      content: " CSS3!!!";
      color: red;
    } // h1 요소 콘텐츠의 뒷 공간에 content 속성 값을 삽입.
  </style>
</head>

🎁 참조 및 출처

profile
무엇이든 할 수 있고, 무엇이든 될 수 있는

0개의 댓글