CSS Scoped Styles

There are plenty of awesome new attributes we've gotten during the HTML5 revolution: placeholder, download, hidden, and more. Each of these attributes provides us a different level of control over an element on the page, but there's a new element attribute that allows control over several elements: scoped . The style element's scoped attribute allows developers to apply styles to only the host element and descendant elements -- a new level of control that CSS hasn't seen in several years.

The only difference in apply scoped styles is adding the attribute:

<style scoped> /* styles go here */ </style>

Scoped styles apply to the current element and descendant elements. Inline styles still win out over scoped styles, so it's still best to avoid using inline styles, even when placing new scoped style elements in the page. An example that illustrates the varying levels of styling could look like:

<div class="democontain"> <style scoped> div { border: 1px solid green; margin-bottom: 20px; min-height: 40px; } .democontain { background: #f8f8f8; } </style> <div></div> <div style="border-color: pink;"> <style scoped> div { background: lightblue; border: 1px solid blue; } </style> <div></div> </div> <div></div> </div>

One interesting experiment result within Firefox Nightly shows that media queries within scoped styles work but only if the media query is a match during the page's initial render:

<style scoped> @media only screen and (max-width : 1024px) { div { background: #000; } } </style>

This may be a bug as the feature has just recently been implemented.