# ::target-text

> The `::target-text` CSS pseudo-element represents the text the browser has scrolled to using a text fragment.

## How do I style text fragment highlights in CSS?

The pseudo-element that styles the text highlighted by a URL text fragment like '#:~:text=example'. Allows customizing how the linked phrase is emphasized when a user follows such a link.

- Topic: Pseudo Elements
- Type: pseudo-element
- Browser support: Chrome 89+, Chrome Android 89+, Edge 89+, Firefox 131+, Firefox Android 131+, Safari 18.2+, Safari iOS 18.2+

## Example

Wrong:

```css
::target-text {
  background: yellow;
  padding: 2px;
  border-radius: 4px;
}
```

Right:

```css
::target-text {
  background: #ffe066;
  color: #111;
}
```

Only text styles apply to `::target-text`, so padding and radius are dropped, and a set text color keeps contrast.

## Common mistakes

- Confusing it with `:target`, which styles the element whose `id` matches the hash.

## Key points

- Colors for `::target-text` keep readable contrast with the text.
- Only text styles like `color` and `background-color` are used; others are ignored.

## Interview questions

### How do I create a text fragment link?

Add `#:~:text=` and the encoded phrase to a URL, like `page.html#:~:text=color%20mix`. The browser scrolls to the first match and highlights it.

### Can JavaScript read the text fragment from the URL?

No. The `:~:text=` part is removed from `location.hash`, so page scripts don't see it.

## Related cards

- [:target](https://wonderium.dev/css/target.md)
- [::highlight()](https://wonderium.dev/css/highlight.md)
- [::selection](https://wonderium.dev/css/selection.md)
- [Pseudo-element](https://wonderium.dev/css/pseudo-element.md)
- [URL](https://wonderium.dev/web/url.md)

---

- Level: [CSS](https://wonderium.dev/css.md)
- HTML version: https://wonderium.dev/css/target-text
- Last updated: 2026-11-25
