A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

:target CSS does not work because shadowRoot does not set a target element

MatteoWebDesigner
2017-03-15

When you click on anchor element like this <a href="#location"> document set a target element internally, activating :target pseudo selector.

This does not happen when your :target element is inside a shadowRoot link to bug.

It turns out that is not a bug and they are following the spec.

In my opinion this is a limitation and ultimately css should work everywhere independently where are used.

At least we should allow shadowRoot to define a target element like document does.

let template = `
	<div>
		<a href="#location">location-1</a>
		
		<h2 id="location">title-1</h2>
	</div>

	<style>
		#location:target {
			background-color: yellow;
		}
	</style>
`;

customElements.define('my-component', class myElement extends HTMLElement {
	constructor() {
		super();
		let shadowRoot = this.attachShadow({ mode: 'open' });
		shadowRoot.innerHTML = template;
		
		window.addEventListener('popstate', function () {
			shadowRoot.targetElement = document.targetElement;
		});
	}
});
simevidas
2017-03-18

Note that this is a temporary WontFix until Tab, Domenic, etc. chime in. The CSS :target selector was defined before web components were a thing, so now the CSS WG has to decide how existing CSS features fit into this.

On the surface, :target should work inside shadow DOM, unless there’s a good reason not to, of course.

MatteoWebDesigner
2017-03-18

Aaah I thought they were not going to fix it. Good to know :).