[CSS 개념 잡기] CSS의 선택자

 

 

1. CSS 선택자

 

선택자(Selector)의 종류

CSS 선택자는 CSS 규칙을 적용할 요소를 정의한다.

 

✔ 주요 선택자

  1. Type 
  2. h2 { color: purple; }
  • 하나의 웹 페이지에서 일괄적으로 적용할 때 사용
  • 대게 CSS 상단부에 작성

 

  1. ID
    #welcome-title {
    color: red;
    }
  • 특정 요소 하나에만 적용되는 유일한 선택자
  • CSS에서 태그 앞에 #을 붙임

 

  1. Class
    .blue {
    color: blue;
    }
  • 스타일을 공통 적용해야 할 요소들을 그룹화 하기 위한 선택자
  • 여러 요소에 중복 가능
  • CSS에서 태그 앞에 .을 붙여 적용



✔ 속성 선택자 - [attr], [attr=value]

요소의 속성을 선택한다.

  1. [attr]
    /* [attr] */
    a[target] {
    color: hotpink;
    }
  2. [attr=value]
    /* [attr=value] */
    a[href="#"] {
    color: blue;
    }
  • input 태그는 type에 따라 여러 형태가 존재하기 때문에 속성 선택자를 활용
    input[type="submit"] {
      background-color: green;
    }

 

 

✔ 속성 선택자 - [attr^], [attr$], [attr*]

  1. [attr^]
    /* [attr^=value] */
    a[href^="http://"] {
     color: red;
    }
  • ^: 해당 value로 시작하는 모든 속성을 선택

 

  1. [attr$]
    /* [attr$=value] */
    a[href$=".com"] {
     color: silver;
    }
  • $: 해당 value로 끝나는 모든 속성을 선택

 

  1. [attr*]
    /* [attr*=value] */
    a[href*="value"] {
    color: sienna;
    }
  • *: 해당 value가 적어도 1개 들어있는 모든 속성을 선택

 

 

✔ 가상 선택자 - first-child, \ast-child, nth-child

범위를 좁히는 역할

  1. [first-child]
    li:first-child {
     color: green;
    }
  • 형제들 중 첫 번째 자식 요소를 선택
  • ⚠ 부모의 첫 번째 자식에 해당 선택자가 적용 되어있지 않으면 first-child css 적용 안됨 last, nth도 동일함

 

  1. [last-child]
    li:last-child {
    color: tomato;
    }
  • 형제들의 부모의 마지막 자식

 

  1. [nth-child]
    li:nth-child(n) {
    color: yellow;
    }
  • 형제들의 부모의 n번째 자식 
  • li:nth-child(2n) { color: red; }
  • () 안에는 수식도 가능함 ex) 2n, 2n-1, odd ...

 

 

✔ 가상클랙스 선택자 - first-of-type, last-of-tyle, nth-of-type

child는 부모를 기준으로 배정되었기 때문에 원하는 결과를 얻지 못할 수 있다. 이를 보완한 것이 type이다.

p:first-of-type {
    color: red;
}

P:last-of-type {
    color: blue;
}

p:nth-of-type(2) {
    color: pink;
}
  • 문법은 child와 차이가 없음
  • 특정 type들만 모아 센 후, 그 중에서 순서를 결정함
  • child 대신 type만 써도 될까?
      .movie:first-of-type {
        color: red;
    }
    • type은 div, p 두 가지 요소를 그룹화하기 때문에 각 요소의 첫 번째 자식에 적용함

 

 

✔ 가상클래스 선택자 - not

앞 selector를 선택 하되, not 속에 들어있는 selector는 제외한다.

/* selector:not(selector) */
input:not(.pw) {
    background-color: red;
}

/* attr도 적용 가능 */
input:not([type=submit]) {
    background-color: red;
}

 

 

✔ 가상클래스 선택자 - link, visited

동적 가상 클래스 선택자이다. 하이퍼링크에 적용한다.

<a href="http://example.com">Example Link</a>
  • 링크는 처음엔 파란색이었다가 한 번이라도 방문한 적이 있다면 보통 보라색으로 변함
  • link : 처음 보이는 색 적용
  • visited : 한 번이라도 방문했던 링크에 색 적용
    a:link {
      color: tomato;
    }
    a:visited {
      colot: yellowgreen;
    }

 

 

✔ 가상클래스 선택자 - enabled, disabled, checked

input 요소에 사용하는 가상 클래스이다.

/* 활성화된 요소에만 적용 */
input[type=text]:enabled {
    background-color: skyblue;
}

/* 비활성화된 요소에만 적용 */
input[type=text]:disabled {
    background-color: silver;
}

/* 체크된 요소에만 적용 */
input[type=radio]:checked {
    outline: 3px solid red;
}

input[type=checkbox]:checked {
    outline: 3px solid blue;
}

 

 

✔ 가상요소 선택자 - before, after

실제로 존재하지 않는 요소를 만들거나, 범위를 만들어서 스타일을 적용한다.

.movie::before {
    content: 'MOVIE',
    color: red;
}

.favorite::after {
    content: 'star',
}

 

 

✔ 가상요소 선택자 - first-letter, first-line, selection

  • ::first-letter
    • 각 요소의 첫 번째 글자에만 적용
    • ::before와 같이 엮이면, ::before의 첫 번째 글자에 적용 됨
  • ::first-line
    • 각 요소의 첫 번째 줄에만 적용
  • ::selection
    • 드래그한 영역에 적용
      .lorem::selection {
      background-color: blue;
      color: white;
      }

 

 

✔ 선택자 결합 - 하위, 자식

  • 하위(자손)
    • 스페이싱으로 하위 요소를 표현
      ul li:last-of-type {
      colors: red;
      }
  • 자식
    • 자손들 중 바로 밑 자식에게만 적용
    • >로 표현
      ul > li:last-of-type {
      colors: red;
      }

 

✔ 형제 선택자, 그룹화

  1. 일반 형재 선택자 결합 : ~
    뒤에 들어가는 selector는 앞의 selector보다 무조건 뒤에 있어야함
code ~ p {
    color: red;
}

 

  1. 인접 형제 선택자 결합 : +
    앞 selector 바로 뒤에 있는 형제만 지정할 수 있음
code + p {
    background-color: blue;
}

 

  1. 그룹화 : ,
    함께 적용하고 싶은 스타일이 있을 때, 즉 여러 개 선택할 때 사용
p, span {
    color: purple;
}

 

 

✔ 범용 선택자 - *

* {
    color: red;
}
  • 전체 요소에 적용 가능
  • 가장 상단에 작성
  • 와일드카드처럼 사용되기도 함(우선순위 높음)
    div + * {
      color: red;
    }
  • .red, #red는 원래 앞에 *가 붙어 있던 걸 생략 한 것

 

✔ 상속 제어하기 - initial

상속 받고 싶지 않을 때 사용한다.

div {
    border: 1px solid silver;
    margin: 2px;
}

.parent {
    color: blue;
    font-size: 7px;
}

/* child2는 parent의 상속을 받지 않음. */ 
.child2 {
    color: initial;
    /* all: initial; 모든 걸 상속받고 싶지 않음 */
}

 

 

✔ 상속 제어하기 - inherit, unset

div {
    border: 1px solid silver;
    margin: 2px;
}

.child1 {
    color: red;
}

.parent1, .parent2 {
    color: blue;
}

/* inherit : initial과는 반대. 부모의 것을 상속 받음 */
.parent2 * {
    color: inherit;
    /* all: inherit; 모든 걸 상속 받음 */
}
/* unset
1. 상속 받을 값이 있음 : inherit;
2. 상속 받을 값이 없음 : initial; */             
/* only 부모만. 그 위의 요소 신경x */
.parent2 .child1 {
    all: unset;
}

 

 

✔ 우선순위(중요🤯)

  1. 선언된 곳
  2. 명시도 - 적용 범위가 적을 수록 명시도가 높음
  3. 코드 위치
    !important > inline > ID > Class / attribute / pseudo class > Type(tag) > * > inherited

    !important를 남용하지 말아야 함!!!!