Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS ::selection으로 텍스트 선택 색상 재정의하는 방법

웹 페이지에서 텍스트를 드래그해 선택하면 일반적으로 파란색 배경이 나타납니다. CSS에서는 ::selection 가상 요소(pseudo-element)를 사용하면 이 기본 선택 색상을 원하는 대로 자유롭게 재정의할 수 있습니다. 배경색과 글자색을 모두 지정할 수 있으며, Firefox 브라우저와의 호환성을 위해 ::-moz-selection도 함께 작성해 주는 것이 좋습니다.

예제

<!DOCTYPE html>
<html>
<head>
<style>
   ::-moz-selection {
      color: rgb(255, 255, 255);
      background: rgb(118, 69, 231);
   }
   ::selection {
      color: rgb(255, 255, 255);
      background: rgb(118, 69, 231);
   }
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   p {
      font-size: 40px;
   }
</style>
</head>
<body>
<h1>Text selection color example</h1>
<h2>Select some text to see the text selection color</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto consequuntur fugiat 
doloremque adipisci vero iste soluta ea ut! Exercitationem rem dolore delectus modi 
repellat quo mollitia temporibus laudantium, alias itaque tempora, iure voluptatem 
non voluptas, deleniti laborum? Cum ducimus unde, vitae consequuntur nobis dignissimos 
similique officia possimus quis necessitatibus praesentium!
</p>
</body>
</html>

출력 결과

위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

CSS ::selection으로 텍스트 선택 색상 재정의하는 방법

본문의 텍스트를 마우스로 드래그해 선택하면, 아래 스크린샷과 같이 기본 파란색 대신 보라색 배경에 흰색 글자가 적용된 것을 확인할 수 있습니다.

CSS ::selection으로 텍스트 선택 색상 재정의하는 방법