2013-07-02

Scoped Styles?

HTML5 and CSS3 have thrown a lot of useful things our way, border radius, web workers, gradients, the history api ... the list goes on!

One of the lesser known features is the ability to add scope to CSS styles, meaning you can inline css in a style tag and have it apply only inside of the style elements parent.

See an example below:


		<div class="plugin-container">
			<style scoped>
				p { color: red; }
			</style>
			
			<p>This text should be red!</p>
		</div>
		

(you can see the above example in action here)

"But where could this be useful!?" I hear you cry! Initially I had to think for a bit before coming up with some uses for this, but after a short while, a few come to mind.

Most notably, this could be very useful when developing a plugin/extension for use either on your site or other peoples sites (through use of an iframe). Using an external stylesheet doesn't offer any benefits here, in fact it would be to the detriment of the end user due to an extra HTTP request. The scoped attribute is useful in that it means you don't need to give the elements ridiculous names to ensure the class/id is not already defined. It also simplifies managing the plugin/extension to an extent as everything is in one place.

This could also be incredibly useful for future CMSes, if a user made changes to certain elements the CMS could create a scoped style element to ensure that the styles only effect the content being edited.

But isn't seperation of concerns a good thing? How does this even degrade?

Both of the above are however good points, seperation of concerns is good practise, and using scoped style elements doesn't really adhere to this.

Browser support is also incredibly dissapointing. As of writing this, only Firefox supports this feature, and even then only from version 21.

This also doesn't degrade, if a browser doesn't support scoped styles then the inline styles will take precedence, potentially ruining said page. You can see this in action by viewing the earlier example in any browser that isn't Firefox.

This doesn't mean that I think this feature is pointless, or useless, far from it. While use cases are admittedly few and far between, I look forward to the day when this will be fully supported across all popular browsers.

Linkedin Stackoverflow GitHub

About Me

I'm a web developer (mostly Front end) currently working at Studio 24 (I previously worked for an Essex based company called Intelligent Penguin).

I spend a fair amount of time messing around on the web, I'm reasonably active on Stackoverflow (link above) and I've been known to tweet occasionally.

I started this site primarily as a blog, I find it useful to write about what I learn and that's what I intend to do (hopefully my ramblings are useful to someone)!