CSS에는 가상 선택자인 가상 클래스(:pseudo-class)와 가상 요소(:pseudo-element)가 존재한다.
가상 선택자를 활용함으로써 html 문서의 수정 없이 CSS만으로 디자인적 요소를 추가할 수 있다.
선택자: 가상클래스 { property: value; }
가상 클래스(:pseudo-class)는 화면의 특정 요소에 커서가 향했을 때 디자인을 입혀주는 등 어떤 요소에 동적인 스타일을 입혀주는 역할을 한다. 실제로 존재하는 요소에 클래스 추가 없이 디자인을 입힐 수 있다.
반면, 가상 요소(Pseudo-element)는 실제로 존재하지 않는 요소를 만들어 주는 역할이다.
마우스가 해당 요소 위에 있을 때 요소의 스타일 변경
input { width: 100%; background-color: white; } input:hover { background-color: blue; }
마우스가 해당 요소를 클릭하는 순간부터 떼는 순간까지 요소의 스타일 변경
input { width: 100%; background-color: white; } input:active { background-color: gray; }
마우스로 해당 요소를 클릭하면 요소의 스타일 변경
input { width: 100%; background-color: white; } input:focus { background-color: red; }
:link
는 아직 방문하지 않은 링크
:visited
는 이미 방문한 링크a:link { color: blue; } a:visited { color:purple; }
:first-child
: li 중 첫번쩨 요소에 해당 CSS를 적용
:last-child
: li 중 마지막에 해당 CSS를 적용
:nth-child(n)
: li 중 n번쩨 요소에 해당 CSS를 적용ol li:first-child { border-top: none; } ol li:last-child { border-top: none; } ol li:nth-child(2) { border-top: none; }
::before
와::after
는 생성된 콘텐츠의 내부에 삽입된다.이 요소는 특정 요소를 풍부하게 해주며, 보통 이미지나 글, 그라데이션 등을 삽입하는 경우가 많다.
h1::before { content: 'hello'; } h1::after { content: url("images.gif"); }