CSS

Css선택자 - 가상 요소(Pseudo Element)로 사용하기

dd-frontend 2024. 5. 28. 20:57

가상 요소(Pseudo Element)

가상 요소는 실제 HTML 페이지에 요소가 존재하지 않지만, 요소가 추가된 것과 같은 효과를 내는 CSS 선택자입니다.

CSS에 컨텐츠("content") 속성을 가지는 일부 가상 요소는 웹 브라우저 개발자 도구에서도 하나의 요소로 처리되며, HTML 소스 보기에서 별도로 가상 요소가 함께 표시가 된다.

가상 요소는 총 5개.
가상 요소는 블록 요소에만 사용할 수 있고, 블록 요소에 추가의 요소가 블록 요소 앞/뒤에 덧붙는 형태로 구현된다.

::before

요소 앞에 가상 요소 'content' 속성으로 입력한 내용을 표시.
"::before" 가상 요소는 속성으로 "content"가 있으며, "content" 속성에 표시할 텍스트 내용이 있어야 가상 요소가 표시된다.

HTML 문서 안에 반복적으로 나오는 같은 태그 앞에, 또는 반복되는 목록, 문단(들) 앞에 공통으로 적용할 테스트 내용, 아이콘, 배경 이미지 등을 표시할 수 있다.

::after

요소 뒤에 가상 요소 "content"속성으로 입력한 내용을 표시한다.
"::after" 가상 요소는 속성으로 "content"가 있으며, "content" 속성에 표시할 내용이 있어야 가상 요소가 표시된다.

다음 코드 예시에는 <p>태그 앞에 Note: 가 붙는다.
<p>태그 뒷 부분에는 :End가 붙는다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>::before Pseudo-element Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>::before Pseudo-element Example</h1>
<p>1st Sample</p>
<p>2nd Sample</p>
<p>3rd Sample</p>
</body>
</html>
p::before {
    content: "Note: ";
    font-weight: bold;
    color: #007bff;
}
p::after {
    content: ":End ";
    font-weight: bold;
    color: #007bff;
}

::first-line

첫 번째 행을 선택하는 가상 요소이다.
웹 브라우저 너비에 따라 첫 번째 행의 길이는 자동으로 정해짐.
문단, 또는 페이지의 첫 행을 강조하기 위해 다양한 텍스트 효과를 첫 행에 적용할 수 있다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>::first-line Pseudo-element Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>::first-line Pseudo-element Example</h1>
<p>This is a paragraph to demonstrate the ::first-line pseudo-element. Only the first line of this paragraph will be styled differently, making it stand out from the rest of the text.</p>
</body>
</html>
p::first-line {
    font-weight: bold;
    color: #007bff;
    font-size: 1.2em;
}

::selection

마우스 드래그로 선택한 영역에 CSS 스타일을 적용하는 가상 요소.
HTML 전체에 적용하려면 ::selection{} 으로 속성을 부여해 전역으로 적용 가능.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>::selection Pseudo-element Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>::selection Pseudo-element Example</h1>
<p>This is a paragraph to demonstrate the ::selection pseudo-element. Select this text to see the custom selection styles applied.</p>
</body>
</html>
::selection {
    background-color: #ffeb3b; /* Yellow background */
    color: #000; /* Black text */
}

 

 

출처: HTML&CSS 마스터북