CSS ::selection
The ::selection pseudo-element in CSS allows you to apply specific styles to the portion of a document that has been highlighted (or selected) by the user. This customization can enhance the user experience and make your content more visually appealing.
Basic Usage
To use the ::selection pseudo-element, you simply specify the styles you'd like to apply within your CSS ruleset. Below is an example of how to change the background color and the text color of a selected portion of text.
/* CSS code example */
::selection {
background-color: #ffcc00; /* Highlight color */
color: white; /* Text color on highlight */
}
Extended Styles
You can also apply additional properties such as font-weight or text-decoration to enhance the selection style. Here’s an example:
/* CSS code example */
::selection {
background-color: #007acc; /* Highlight color */
color: white; /* Text color on highlight */
font-weight: bold; /* Make the text bold */
}
Browser Support
While the ::selection pseudo-element is widely supported in modern browsers, it is always a good idea to check compatibility if you need to support older versions. Here’s a quick table summarizing browser support:
| Browser | Support |
|---|---|
| Chrome | Yes |
| Firefox | Yes |
| Safari | Yes |
| Internet Explorer | No < 9 |
Conclusion
The ::selection pseudo-element is a powerful tool for customizing the appearance of selected text on your web pages. With just a few lines of CSS, you can significantly improve the aesthetics of your content and enhance user interaction.