Highlights and specialized states
Definition and purpose
Highlight pseudo-elements style ranges of text rather than creating ordinary layout boxes. ::selection styles user selection; ::highlight(name) styles named ranges registered through the Custom Highlight API. Other specialized selectors such as :focus-within match element states instead of text ranges.
Inherited highlight color
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } #parent::selection { color: white; background: navy; } #b::selection { background: green; } </style> </head> <body> <section id="parent"> <p id="a"> Select <span id="b">this text</span> . </p> <label for="x">Search</label> <input id="x"> </section> </body></html>The span highlight inherits white text while overriding its background. Select the text to inspect it.
Syntax and mental model
Highlight inheritance is special: a child highlight can inherit ordinary highlight styles from the ancestor highlight as well as its originating element. Custom properties instead come from the originating element. Use :root::selection for a document-wide inherited default rather than *::selection, which matches each element and can interrupt highlight inheritance. Only a limited set of paint properties applies.
Focus within a region
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } #parent:focus-within { outline: 3px solid navy; } </style> </head> <body> <section id="parent"> <p id="a"> Select <span id="b">this text</span> . </p> <label for="x">Search</label> <input id="x"> </section> </body></html>Tab into the input; the region gains a visible outline.
Common mistakes
Do not use highlight padding or sizing to reserve layout space. Avoid making selection text unreadable; selection and focus are separate interactions and need separate cues.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Shadow DOM and custom states. Next lesson: Complete cascade sorting.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Highlights and specialized states — knowledge check
Five questions on highlights and specialized states.
What does ::selection style?
What can register arbitrary highlight ranges?
Where do highlight custom properties inherit from?
Which selector matches a region containing focus?
Can ::selection reserve layout space using padding?