Skip to main content

On This Page

Styling ::search-text and Other Highlight-y Pseudo-Elements

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

The Different Types of Highlight Pseudo-Elements

Chrome 144 recently shipped the ::search-text pseudo-element, enabling styling of find-in-page matches—text highlighted when using Ctrl/Command + F. Currently, matches default to yellow and the current target (::search-text:current) is orange, but these colors can be modified.

Why This Matters

Ideal CSS models assume consistent rendering across browsers, but reality often requires workarounds for accessibility and usability. The default highlight colors may not offer sufficient contrast, impacting users, and customizing them was previously difficult. Poorly highlighted text can hinder task completion and frustrate users.

Key Insights

  • Pseudo-element proliferation: Six highlight-related pseudo-elements now exist (::search-text, ::target-text, ::selection, ::highlight(), ::spelling-error, and ::grammar-error).
  • Relative Color Syntax: Utilizing rgb(from ...) allows dynamic color adjustments based on the container’s background.
  • Accessibility First: Highlight styling should prioritize color contrast and visual distinction for diverse users and overlapping highlights.

Working Example

body {
  --background: #38003c;
  background: var(--background);
  mark,
  ::selection,
  ::target-text,
  ::search-text {
    color: var(--background);
    background: rgb(from var(--background) calc(255 - r) calc(255 - g) calc(255 - b));
  }
}

::search-text:current {
  background: rgb(from var(--background) calc(255 - r) calc(255 - g) calc(255 - b));
}

Practical Applications

  • E-commerce Search: A retailer could use ::search-text to style search query matches on product pages for improved callout.
  • Pitfall: Over-reliance on default highlight colors leading to accessibility issues for users with low contrast perception.

References:

Continue reading

Next article

Surging Cyberattacks in Latin America

Related Content