Conditional tag for changing structure based on media queries

The problem: designing pages for multiple devices means using media queries in CSS to hide and show parts of the page based on device sizes, capabilities, or preferences. These hidden sections of markup still participate in the DOM, which can cause problems like duplicate IDs breaking form accessibility, or slowing down parsing when querying the DOM or changing styles.

Proposed solution: Similar to the <noscript> tag, which removes its descendants from participating in the DOM (does not download assets and does not parse CSS or JavaScript included inline), a generalized tag could wrap sections of markup to be included only when a media query matches.

Example: The following image and CSS assets would not be requested on devices with a viewport less than 1200px wide.

<when media="(min-width: 1200px)">
  <img src="big_pic.png">
  <link href="large.css" rel="stylesheet">

A similar problem space is changing element attributes based on media queries. With the <picture> element, we can change an img element’s src attribute, but it would be helpful to extend this to other elements and other attributes.


  1. Change a video to play inline (instead of fullscreen) when on a small screen in portrait mode. Enable autoplay when user preferences indicate it’s ok.
  <source media="(max-width: 400px) and (orientation: portrait)" attr="playsinline">
  <source media="(prefers-reduced-motion: no-preference)" attr="autoplay">
  <video src="vid.mp4></video>
  1. Change the input method for an image file upload based on device orientation.
  <source media="(orientation: portrait)" attr="capture" value="user" >
  <source media="(orientation: landscape)" attr="capture" value="environment" >
  <input type="file" accept="image/*" />

How would you handle situations where the media query results change dynamically (e.g. user resizes the window, turns their device, switches a preference, etc)? It seems this would require browsers to keep a copy of the original markup “for reference” somewhere and then dynamically swapping out DOM nodes?

Yep, the browser would do the hard work and heavy lifting to make authoring easier.

Where nodes need to be stable (e.g. when they have listeners attached) the attribute version would only change the attributes of the node and not substitute a whole new node.