[csswg-drafts] [selectors] pseudo-class to select the target of an anchor or label (#11300)

alvaromontoro has just created a new issue for https://github.com/w3c/csswg-drafts:

== [selectors] pseudo-class to select the target of an anchor or label ==
## Description

This would be a new feature, a pseudo-class that selects the target of another element (mainly a label or an anchor). That is, the element with the `id` attribute indicated in a targeting attribute in the original element. Some examples of "targeting attributes":

- The `for` in a `<label>`
- The `href` in an `<a>` (only if it starts with a `#`, this may be a problem?)
- The `aria-controls` in a `<button>`
- The `form` in a `<button>`

Similarly to how the `for` or `href` attributes work, this pseudo-class would only return a single element: the first element in the document with an `id` that matches the targeting attribute.

If no element matches the selection, or if the selected element is non-labelable (in the case of a label's `for`), then the new pseudo-class would have no effect and select nothing.

## Use cases

- Styling a label based on the input attributes or state.
- Styling an anchor based on if the target is active or if it has focus.
- Highlighting a form or tab when the person hovers an outside button that triggers it.
- Selecting the target element to style it differently in certain conditions.

## Examples

In this examples, I will use `:for` as the name of the pseudo-class. 

### Adding a required message into a label for a required input

We may want to style the label to add a "*required" text behind it if the associated input has the `required` attribute. Inputs and labels can be organized in many different ways: the input can go inside the label, right before/after the label, or be completely separate from its label. So we may need different selectors (`input + label`, `label + input`, `label:has(input)`...), which would be simplified with this pseudo-element:

```css
label:where(:for:required)::after {
  content: "*required";
  color: red;
}
```

### Highlighting a footnote on hover

We have a block of text with links to footnotes. If we want to highlight the footnotes on hover, we'd need to write specific selectors for each `id` and they could become really complex if the text with the links is in a container while the footnotes are in another. Having a pseudo-class that selects the target would simplify this:

```css
.has-footnote:hover:for {
  background: #ffc;
}
```


Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/11300 using your GitHub account


-- 
Sent via github-notify-ml as configured in https://github.com/w3c/github-notify-ml-config

Received on Saturday, 30 November 2024 15:16:59 UTC