pseudo-class

요소의 특정한 상태를 정의하기 위해 사용하는 CSS 속성이다.

  • 사용자가 마우스를 올렸을 때, 요소를 스타일링 하기
  • 방문한 링크와 미방문 링크 스타일 구분하기
  • focus가 잡혔을 때, 요소 스타일 주기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* unvisited link */
a:link {
color: #ff0000;
}

/* visited link */
a:visited {
color: #00ff00;
}

/* mouse over link */
a:hover {
color: #ff00ff;
}

/* selected link */
a:active {
color: #0000ff;
}

a:hover는 a:link, a:visited 속성 이후에 선언되어야한다. 또한 a:active 속성은 a:hover 속성 이후에 선언되어야 한다.

:first-child pseudo-class

요소의 첫번째 자식을 선택하는 선택자이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<style>
p:first-child {
color: blue;
}
</style>
</head>
<body>
<p>This is some text.</p>
<p>This is some text.</p>

<div>
<p>This is some text.</p>
<p>This is some text.</p>
</div>
<section>
<p>this is first element</p>
<p>this is second element</p>
</section>
</body>
</html>

first-child

이 외에도 많은 pseudo-class들이 있으니 필요하면 찾아서 사용하자.

pseudo-element

요소의 특정 부분을 스타일링 하기 위해 사용하는 CSS 속성이다.

  • 요소의 첫번째 줄이나 첫문자를 스타일링 하기
  • 요소 content의 이전이나 이후에 content를 삽입하기

::first-line

첫번째 줄의 특별한 스타일링을 추가하기 위해 사용한다.

  • block level 요소에만 설정 가능하다.
1
2
3
4
p::first-line {
color: #ff0000;
font-variant: small-caps;
}

::first-letter

첫번째 문자를 스타일링 하는데 사용된다.

  • block level 요소에만 설정 가능하다.
1
2
3
4
p::first-letter {
color: #ff0000;
font-size: xx-large;
}

::before

요소의 content 이전에 어떤 content를 삽입하기 위해 사용한다.

1
2
3
h1::before {
content: url(smiley.gif);
}

before

::after

요소의 content 이후에 어떤 content를 삽입하기 위해 사용한다.

1
2
3
h1::after {
content: url(smiley.gif);
}

::selection

사용자에 의해 선택된 부분을 스타일링한다. 아래는 드래그하여 텍스트를 선택하였을 때의 상황이다.

1
2
3
4
::selection {
color: red;
background: yellow;
}

selection