In a recent email to www-style, James Kyle asks for the ability to use inline styles (the style
attribute) to style an element based on pseudo-classes. That is, specify inline how an element should look when it’s hovered/etc, just like you can do today for the general case.
This was proposed over a decade ago in the 2002 Style Attr draft, but it didn’t gain traction at the time and was dropped when the next draft was published in 2010. I’d like to revive this. As James points out in his email, Web Components and new DOM-handling techniques like React have made inline styles more useful than they were in the past, but it still requires going back to a stylesheet to apply hover/focus/etc styling to an element, which is frustrating.
The proposal is simple:
- Define a new grammar production for selectors composed solely of pseudo-classes and pseudo-elements. (There’s no need for any feature selectors in inline style; you already know what attributes/etc the element you’re modifying has.)
- Modify the grammar of the style attribute, to allow style rules containing the pseudo-only selectors to be placed after any inline style declarations. These rules are all scoped to the element they’re written on.
- Lightly modify the Cascade spec to allow for declarations that both come from inline style and have specificity, to get the obvious result - “plain” inline styles lose to selector’d inline styles, and selector’d inline styles use specificity like normal amongst themselves (so
:hover {...}
loses to:first-child:hover {...}
).
This would look like:
<a href="http://www.w3.org/"
style="color: #900;
:link {background: #ff0}
:visited {background: #fff}
:hover {outline: thin red solid}
:active {background: #00f}">...</a>
Note: In the past I’ve argued that intermixing style rules and declarations is grammatically ambiguous, and that’s still true in general. (The issue is that selectors like a:hover
look like declarations.) In this case, tho, we’re limited to just pseudo-selectors, which all start with a :
, which lets us distinguish them from declarations. This is identical to how at-rules are safe to intermix with declarations, because they start with @
.