10.1 의사 클래스
HTML과 CSS의 의사 클래스 및 의사 요소는 요소의 상태나 내용에 따라 스타일을 지정할 수 있게 해줘. 추가적인 클래스 없이도 HTML 문서의 구조를 변경할 필요가 없어. 웹 페이지를 인터랙티브하고 예쁘게 만들 수 있는 멋진 도구를 제공하지.
의사 클래스는 문서 구조에서의 요소 상태나 위치에 따라 적용돼. 마우스 오버나 포커스, 요소 강조 같은 다양한 상황에서 요소 스타일을 지정하는 데 유용해. 의사 클래스는 콜론 (:)으로 시작해.
가장 간단한 의사 클래스:
의사 클래스 :hover는 사용자가 요소 위에 마우스를 올렸을 때 적용돼.
<button type="button">버튼</button>
button:hover {
color: red;
}
의사 클래스 :focus는 요소에 포커스가 갔을 때 적용돼, 예를 들어 입력 필드를 클릭할 때처럼.
<input type="text">
input:focus {
outline-color: blue;
}
의사 클래스 :active는 요소가 활성화될 때 적용돼, 버튼이나 링크를 클릭할 때처럼.
<button type="button">버튼</button>
button:active {
background-color: green;
}
의사 클래스 :visited는 사용자가 이미 방문한 링크에 적용돼.
<a href="#">링크</a>
a:visited {
color: purple;
}
10.2 의사 요소
의사 요소는 별도의 HTML 요소가 아닌 요소의 일부를 스타일링할 수 있게 해줘. 두 개의 콜론 (::)으로 시작해. 의사 요소는 요소 앞이나 뒤에 콘텐츠를 만들거나 첫 줄이나 첫 글자를 강조하는 등 다양한 기능에 사용돼.
가장 단순한 의사 요소:
의사 요소 ::before는 요소의 콘텐츠 앞에 내용을 삽입해.
<p>내 이름은 스테판이야.</p>
p::before {
content: "안녕! ";
color: blue;
}
의사 요소 ::after는 요소의 콘텐츠 뒤에 내용을 삽입해.
<p>주의해!</p>
p::after {
content: " 감사합니다!";
color: red;
}
의사 요소 ::first-line는 요소의 첫 줄에 적용돼. 텍스트의 첫 줄에만 스타일을 적용할 수 있어.
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
p::first-line {
font-weight: bold;
color: green;
}
의사 요소 ::selection은 사용자가 선택한 텍스트에 적용돼.
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</p>
::selection {
background-color: blue;
color: yellow;
}
결과에서 텍스트를 선택해보세요.
10.3 의사 요소 사용 예
HTML과 CSS의 의사 클래스 및 의사 요소는 요소의 상태나 내용을 기반으로 스타일을 지정할 수 있는 훌륭한 도구들을 제공해. HTML 구조를 바꾸지 않고 더 인터랙티브하고 시각적으로 매력적인 웹페이지를 만들 수 있게 해줘.
예제 1: 링크 텍스트 앞에 아이콘 삽입하기
<html>
<head>
<style>
a::before {
content: "🔗";
margin-right: 5px;
}
</style>
</head>
<body>
<a href="#">아이콘이 있는 링크야</a>
</body>
</html>
예제 2: 단락 뒤에 스타일 블록 추가하기
<html>
<head>
<style>
p::after {
content: "🌟";
display: block;
text-align: center;
margin-top: 10px;
}
</style>
</head>
<body>
<p>이것은 텍스트 단락이야.</p>
</body>
</html>
조합하기
의사 클래스와 의사 요소를 조합하여 복잡하고 강력한 스타일을 만들 수 있어.
예제: 링크 안에 선택된 텍스트를 마우스 오버할 때 스타일링하기
<html>
<head>
<style>
a:hover::selection {
background-color: lightblue;
color: navy;
}
</style>
</head>
<body>
<a href="#">이 텍스트를 선택한 다음 마우스를 가져가보세요.</a>
</body>
</html>
GO TO FULL VERSION