Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To what viewport do media queries in Shadow DOM elements apply?

The HTML5 Rocks tutorial on styling the Shadow DOM doesn't discuss media queries. Since the shadow boundary is supposed to provide style encapsulation for free, it would be really neat if @media queries applied to the size of the host element, rather than the viewport of the browser.

This would solve the problem of media queries being a hack when in reality we need @element queries, which as of July 2015 exist only as an abandoned repo on GitHub.

like image 476
Dan Dascalescu Avatar asked Jul 08 '15 07:07

Dan Dascalescu


People also ask

What selector works for shadow DOM elements?

The :host selector allows to select the shadow host (the element containing the shadow tree).

How do shadow DOM root elements interact?

To access the shadow DOM elements using JavaScript you first need to query the shadow host element and then can access its shadowRoot property. Once you have access to the shadowRoot , you can query the rest of the DOM like regular JavaScript. var host = document. getElementById('shell'); var root = host.

How does shadow DOM work?

Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — this shadow DOM tree starts with a shadow root, underneath which you can attach any element, in the same way as the normal DOM.

How do you access the element in shadow DOM?

We can only access the shadow DOM by the reference returned by attachShadow (and probably hidden inside a class). Browser-native shadow trees, such as <input type="range"> , are closed. There's no way to access them.


1 Answers

Alas, no. The @media queries inside the Shadow DOM look at the viewport of the browser, not at the dimensions of the host element.

var root = document.querySelector('div').createShadowRoot();
root.innerHTML = '<style>@media (min-width: 600px) { h3 { color: red; }}</style>' + 
                 '<h3>If this text is not red, you live far in the future</h3>';
<div style="border: 1px solid black; width: 100px"><h3>Light DOM</h3></div>

This is probably because of the circularity issues that might ensue if the Shadow DOM element sized itself in a way incompatible with the host.

like image 189
Dan Dascalescu Avatar answered Oct 16 '22 09:10

Dan Dascalescu