The scoped attribute

by .

The scoped attribute for the <style> element allows you to include styles mid-document that targets a specific element and its children. Depending upon how you look at this, it’ll either be a godsend or a curse. Once you’ve reached the end of this article, I hope you can form your own opinion.

Let’s take a quick look at the spec:

The scoped attribute is a boolean attribute. If set, it indicates that the styles are intended just for the subtree rooted at the style element’s parent element, as opposed to the whole Document.

Isn’t this bad practice?

For years, we’ve been told (and have actively told others) to separate content and presentation layers. So why would we introduce something that seems to go against everything we’ve been preaching?

The separation of these layers is still vitally important, but let’s look at a few use cases to shed some light on why this attribute has been introduced. Scoped style provides a W3C-approved way to:

  • Add one-off CSS styles.
  • Add user-defined styles to wiki or CMS content.
  • Add theme-defined styles via CMS plugins.
  • Keep syndicated content together (e.g., keeping example code together with the example).

How does it work?

In this section, I’ll show you how this new attribute will work when it gets rolled out to browsers.

Our starting point

We’ll be using the following code sample as a starting point:

<article>
  <h1>Style Scoped</h1>
  <p>The scoped attribute for the style element will eventually allow for you to include style elements mid-document. To do this, you must mark up your style element with the scoped attribute.</p>
  <section>
    <h2>How does it work?</h2>
    <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
  </section>
</article>

This is a basic example, with two headings and two paragraphs set within the article element.

Adding the scoped attribute

In the next example, we’ll change the foreground color of the second paragraph to red (from whatever was defined in the master CSS file):

<article>
  <h1>Style Scoped</h1>
  <p>The scoped attribute for the style element will eventually allow for you to include style elements mid-document. To do this, you must mark up your style element with the scoped attribute.</p>
  <section>
    <style scoped>
      p { color: red; }
    </style>
    <h2>How does it work?</h2>
    <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
  </section>
</article>

This screenshot shows how things might render in the browser:

How the scoped attribute will render

Backwards compatibility

Unfortunately, scoped style isn’t all puppy dogs and kittens.

Since this newly introduced attribute isn’t understood by current browsers, CSS rules in <style scoped> are just added to the page’s CSS. Therefore, if you were to include a scoped style block mid-page, its declarations would be applied to every matching element in the document, regardless of whether the element were inside or outside of the scope’s range.

For the sake of backwards compatibility, Louis Lazaris has suggested a brand new element called <scopedstyle>. This new element would only be recognised by supporting browsers and ignored by everything else. This way, scoped styles wouldn’t be added to the whole document. Instead, the browser would just throw away the unrecognised <scopedstyle> element and move on.

Browser support

Browser support for <style scoped> (as of )
Browser Support
Chrome 13 No
Safari 5 No
Firefox 6 No
Opera 11.51 No
Internet Explorer 9 No

Currently, the scoped attribute isn’t working in any of the browser alpha versions (Opera.Next, Mozilla Aurora, or WebKit nightly builds). There’s work in progress by Roland Steiner for support in WebKit.

Using <style scoped> today

So you’ve read this article and decided that you need scoped style in your life. What now? Well, just like every other new HTML5 thing, we have a polyfill for it. Simon Madine has created a jQuery scoped CSS plugin on GitHub.

You could also assign a CSS prefix to target the section of your document you want to style. You’d still be able to stick your styles inline, but you’ve also provided a fallback for the older browsers. In fact, Dr. Oli has done just that on his latest article. (View source and search for <div class="faint">.)

Opinions

There’s no denying that we’re breaking backwards compatibility by introducing <style scoped>. To me, this just doesn’t make any sense. I feel this needs to be addressed by either creating a new element like <scopedstyle> or using some protective mechanism like the <!-- and --> delimiters that have been used within <style> and <script> elements.

Let’s not end this article with negative sentiment, though. As with anything, it’s what you make of it. Scoped style is pretty plain vanilla, but if people abuse it, it’ll end up with a bad rap. Dr. Oli has spoken at length about his love for this attribute as it allows him to have live code examples with the CSS in <pre> and also in a <style scoped> within a <figure>.

So now it’s time for you to express your views. What do you think about the new scoped attribute? Do you think it has a future? Should it be fast-tracked into the spec? Or do you think it’s a waste of time that could ultimately end up mixing our content and presentation layers together again? Let us know in the comments!

85 Responses on the article “The scoped attribute”

  • Patrick Cox says:

    It seems like a great tool for injecting CSS where and when you need it, but I agree, it seems a bit useless right now. I could really see it working with CMS’s and giving the users the ability to style their content without having to hack a CSS file or override other CSS selectors. That could become a big thing.

  • But wouldn’t a new, unknown element result in the content of the element being displayed as plain text in page? You’d then need scripting or something to remove it, introducing even more issues…

  • Miszy says:

    For what purpose should I use this unsupported by all browsers, troubles-causing attribute, while I could use inline styles or unique classes to achieve the same effect?

  • Jess K says:

    What if it was done via CSS instead?


    <section>
    <style>
    @scope element {
    p {color: red}
    }
    </style>
    </section>

    or


    <style>
    @scope "#mysection" { /*just use a selector*/
    p {color: red}
    }
    </style>

    <section id="mysection">
    </section>

    Do browsers ignore the entire block if they don’t understand @scope?

  • Leon says:

    Why not just add a class? Or, if you need inline styles, <p style="color: red;">. Or am I missing something?

  • John Evans says:

    Great article Jack.

    My thoughts are that this could be of certain uses and that like everything if it used in moderation and at the right times it will be fine but if it is abused (as we have seen with so many things) It will quickly get a bad name, as you stated above.

    I’m sure that as time progresses more and more valid uses will come to the forefront and the ones who respect the tags will adapt to it quite well and use it only when needed.

    Anyway: enough of my inane rambling on!
    John

  • Jack Osborne says:

    @Jess — I really like your first suggestion.

    @Leon — Yes, you can add a class.

  • CpILL says:

    This seems to sit between the and the inline style=”” attribute. The later of which has a bad rep for anything other than dynamic styling. This adds a new grain size to style/layout control which i guess is good.

    I think this could be useful in a CMS that has come to the realisation that layout and (some) style is part of the content. That if transported without certain presentation description the text/images content would lose meaning.

    There are plenty of WYSIWYG editors these days that allow content templates to guide the uses data entry. This would be very handy in this situation.

    But there seem to also be all the dangers of inline styling. As a rule if i have to make such specific element styling I make sure its only positional control and never colour/font/border attributres, anything that might need to change if the site style/theme changes.

  • DJ says:

    It occurs to me that pretty much the major use for this would be for those who write code which is scraped (or submitted) into web pages which are not their own; but, for which they want to maintain control over the way their scraped content is styled. Namely, by moving the styling of such code segments BACK into inline styling. [i.e. – if someone wants to scrape your <html> code – then by golly they get the <scope> style along with it].–

    Lets ask a relevant sub-question: We are told that on this HTML5 web doctor site “some HTML is ok” and we can use , , etc. IF browsers start supporting this feature, will the HTML5 doctor site be allowing the <scope> feature as well – which will permit “style injection” onto your site?

    Will this be just another “price to pay for using or posting on the internet” like spam and viruses – i.e. “if you want to scrape code then you’ll just have to put up with my injected styles?”

  • Bernhard Hofmann says:

    The scoped styling is only a small step away from in-line styling on elements, which I think we all agree is evil. It seems like the sort of thing you’d inject into a page when you don’t have control of the mark-up. But then why not just inject a few classes or use some more sophisticated selectors.

    People worked hard to separate CSS and HTML and now CSS is being merged back into the HTML. No; maybe I’m missing something, but I’ve got a dirty feeling about this.

  • Tim Hettler says:

    Even with a theoretical 100% support – I can’t foresee a situation where this approach would be acceptable to use in a production environment. It has all the same maintenance & performance issues of inline styles.

    This attribute would make creating code examples nice and tidy, however. Perhaps that’s reason enough to implement it.

  • Svafa says:

    As others have pointed out, I could see it working well within a CMS, especially in a situation where the layout needs to be preserved, but also in the situation where the content editor does not have access to the css or the document head.

    The latter is often the case where I work, and currently those tech-savvy editors in need of some more sophisticated styling than allowed by the editor start dabbling with inline styles. The scoped attribute could give them a little more control over their content without opening up the css for the entire page. But in this case I would recommend a separate element, like <scopedstyle>, so a user is less likely to accidentally insert a <style> element in the middle of the body and forget to include the scoped attribute.

  • mstalfoort says:

    how will this affect the rendering of the page performance wise?
    isn’t this just creating a ‘blocking’ rendering

  • Konstantin Vayner says:

    Why not use ID ?

    If you need to inject style relevant only for specific scope, give scope container an ID and start the selectors with that #ID …

    This functionality already exists, why introduce yet-another-way of doing the same thing?

  • Simon says:

    Seems to me that the lack of backwards compatibility just makes this worthless. If a browser not recognising the scope is going to just apply the style to the entire document, breaking the entire page layout – well, why would I bother using it?

  • While I could see some interesting use cases (especially in the case of syndicated content that doesn’t appear in iframes), it’s a shame that the solution isn’t more generic.

    For now you can scope the styles for a particular section in your document, but you still can’t block that section from any previously defined styles. So even if you would include syndicated content with a specific stylesheet, it would still conflict with your own styles.

    I wrote about this problem (http://www.onderhond.com/blog/work/css-boundaries-stopping-the-cascade) 3 years ago, but little has been done to fix this I’m afraid.

  • Jon B says:

    Hmm, I’m not convinced this is really the best way to a solve the problem. Typically I imagine the perfect case for something *like* this would be widgets from other sites, or JS widgets that rely on CSS for their styling. However these styles seem to just be added to the exisiting inherited styles already affecting the element :/

    I’d personally prefer a scoped style block to be able to reset the inherited styles completed. That should at least be an option. I think CSS as a whole needs this option. Yes it could be horribly misused and allow people to use CSS poorly, but on the otherhand it would allow far cleaner and more reliable CSS for specific situations where an set of elements is negatively affected by inheriting loads of cascaded styles, which would otherwise have to be reset individually.

  • Phunky says:

    I can see a use for this for things like the Facebook Social plugins and you may want and additional separation from internal & external css declarations but other than that it feels a little dirty.

  • Hernan says:

    I really like the idea for widgets, syndicated content and the like. Would make some things easier.

    I don’t like that is and all or nothing and that needs to be declared somehow in the middle of your markup.

    It could make more sense that ‘scoped’ take a css selector (id, class, combination of them) as the value.

    That way it could be easier to work some backguard magic via a js shim.

  • Phunky says:

    Hernan that makes perfect sense :) love the idea.

  • Alohci says:

    I wonder if something like <style type=”text/scoped+css”> would have a better backward compatibility story. Legacy browsers would recognise the style element and wouldn’t attempt to render its contents, but wouldn’t recognise the content type so wouldn’t treat it as css. New browsers could recognise it like <style scoped> is intended to do.

  • John Allsopp says:

    I think I can honestly say, I’ve never seen a worse proposed feature of CSS/HTML

    When will these scopes ever be independent of the structured mark-up of the content?

    What cowpath does this one pave, supposedly an important design principle of HTML5

    Frankly, this is a feature I hope is taken out the back and put down pronto.

    john

  • Shelley says:

    What John Allsopp said.

  • Alohci says:

    @John Allsopp – IIRC, one cowpath was essentially the widespread use of inline styles. Inline styles have some problems (beyond mixing presentation and content), most notably you can’t define different CSS for different media types. i.e. You can’t do @media aural in them, which is an accessibility problem. <style scoped> was designed in part to address that issue.

  • John Allsopp says:

    @alohci

    sure, but these are such edge cases, that to introduce a feature that so strong undermines the core principle of separation of structured content and presentation needs to be really really really well justified.

    Off the top of my head, allowing link elements in the body, and scoping the linked style sheet to the parent element (which is close to what link in the head does anyway) solves the problem, introduces zero new elements, and does not inject CSS directly into the markup.

    Inline styles are a hack, which if they’d never been invented, no one would see the need for. Basically, they are so widely used because many CMS lock developers out of anything but the body of a page – or at least used to.

    This is a really really badly thought through non solution to a edge case problem.

    And, I will work tirelessly to ensure it dies a quick death. Truly.

  • Nathan says:

    It is just as easy to add a class – keeping content and presentation separate – to the or maybe to its parent and using a selector of section p.classname. In either case, the class can be updated in a single location as opposed to the possibly many instances where a is styled via .

    Content and presentation concerns aside, does this method take similar precedence as an inline style, such that an external stylesheet cannot override it, nor a user-defined stylesheet where this could impair accessibility?

  • Nathan says:

    Sorry for the double-post, but I wasn’t aware the tags would be stripped out before my last post.

    It is just as easy to add a class – keeping content and presentation separate – to the ‘p’ or its parent ‘section’ and using a selector of ‘section p.classname’. In either case, the class can be updated in a single location as opposed to the possibly many instances where a ‘p’ is styled via ‘style scoped’.

    Content and presentation concerns aside, does this method take similar precedence as an inline style, such that an external stylesheet cannot override it, nor a user-defined stylesheet where this could impair accessibility?

  • This is a badly designed solution for something where no solution is needed.

    Please remove this feature before anyone actually starts implementing it / using it.

  • I see how it works, I was thinking for the most part “just use style=” but then of course you can only target that tag. If I wanted all of the anchors in a specific to change colour, I would have to add style=”” to each anchor.

    Essentially it’s an advanced, more contextually aware version of using the style attribute.

  • ‘section’ was removed from my my last post. (…anchors in a specific section)

  • I’ve been waiting so long for this! We’ve already been doing it but it’s nice for it to be valid code now.

    All the browsers already render what’s in style tags included on the page, they just ignore the scope. Add a class to the parent and you have instant backwards compatibility. I *like* that it works the way it does rather than being backwards compatible by not working at all.

    We use it with our javascript widgets. For example: we have a widget that pulls in RSS feeds. The widget is included on the page by the CMS at the place on the page the user wants to put it. Our CMS does not have hooks to include stuff in the head so the associated script and style files have to be included right there on the page.

    Rather than link to or import a file to include 10 lines* of CSS, for speed reasons we include it on the page (it’s still managed one location thanks to the CMS templates). * sure we could include it in the global style sheets but this is not an insignificant number once you do that for 10 widgets.

    I would hate to see this feature go because of the potential for abuse as it is a useful tool in my box already.

  • I did have a bit of a problem with it the other day. I assumed, incorrectly that <style> is not an element one can target… turns out, no, you can style a <style> and if you have any styles defined for :first-child they apply to it and not to the first visible style. Here’s the blog post if you’re interested.

    Makes me want a display:not-in-flow or something like that.

  • … they apply to it and not to the first visible _element_.

  • John Allsopp says:

    Hi Steph,

    the question is, should we be creating new ways of doing things, which violate long standing best practice, in order to cater to broken CMS? That’s more or less why inline style still exists, AFAICT.

    And, as you point out, you effectively have a solution already for this.

    As style is already allowed and supported in the way you describe, and all you need to do is to scope using class or id, why do we need to do this?

    john

  • Hey John,

    style tags in the body

    The problem with our current solution is that style is not already allowed and supported in the way we are using it :( Not in HTML4 not in XHTML. It was one of my main reasons for going to HTML5.

    I don’t need scope, scope can go (but I feel like it is a better practice to have scope than to not have it since styles in the body can then be abused to re-style the whole page) but I really really want style inside the body tags.

    It takes quite a sophisticated back end programmer to configure a CMS to insert style and script files into the head of a document when you’re coding in the middle of the page. Our CMS runs primarily on SSI includes which means it doesn’t respond in the head to things being done in the body. SSIs are still around, aren’t they? They’re very accessible to new developers, we’re not the only ones still using them are we?

    Inline code

    I have also yet to find a way* to make a container the same width as its contents without inline styles:

    <div style="width:263px;">
    <img width="263px">
    <p>Caption that spans multiple lines but does not exceed the width of the image.</p>
    </div>

    *yeah, one could put that inline style in the head but do I need a class for every conceivable image width? Do I need an ID for one element for one attribute? How do I make sure the next developer removes the styles declaration from the head if they remove the element?

    Until I have a way of doing that, I’m going to remain reluctantly resigned to inline styles as a necessity.

    Really wish I could preview this… crossing my fingers the code comes out okay…

  • John Allsopp says:

    Since style is currently supported in all browsers (tested IE7 up, not sure about IE6) in the way you are using it, I’d reluctantly accept formalising this reality. It’s really the adding of scope that is the big challenge to me – and as you already have a solution using class, it’s hard to see why we need to go further than is necessary.

    There are always going to be edge cases, and frustrating aspects to any development, particularly with the web – I think however it is really really important to ensure we only add features after considerable discussion and consideration. The default position IMO should be, features should not be added, unless an incredibly compelling case can be made.

    Perhaps it would be worth thinking through what such a case would look like in general.

    I would say the following criteria should be met

    1. does not significantly violate several design principles of HTML
    2. it enables something that is otherwise impossible, or very very difficult to achieve otherwise. That is, it should not be merely a convenience, or a sop to broken CMS etc
    3. there is a strong demonstrated need for the feature

    j

  • Benjamin Knight says:

    I think the added flexibility is a good thing, especially for application development. We should still encourage and teach good web design via separation of content, presentation, and behavior. There are advantages to it, just like there are to embedded and inline CSS.

    This also seems to go hand in hand with sectioning elements and HTML5 outlining, that is it can serve to further “modulate” content.

  • Nathan says:

    There is no advantage to using inline CSS except that it can’t be overruled; it hurts accessibility and is indicative of poor planning and design.

  • Benjamin Knight says:

    @Nathan false. It can be overruled using !important. Inline CSS is also essential for manipulating styles using DOM scripting. It’s also convenient for styling one single element and you can actually save bytes that way.

  • Nathan says:

    @Benjamin, thanks, I stand corrected; I was confusing that with !important precedence. I understand you can save a few bytes, but is that advantageous over using a class? While class=”…” might add a few bytes in some cases, style=”property:value” will be a longer string of text. To say it is useful for DOM scripting I understand, but to say essential, suggests it is the only option in a particular scenario. What is an example scenario where it is essential, such that a class would not be sufficient for DOM scripting?

  • nd_macias says:

    I see no point of using scope. Of course it pretty much comfortable to use it somewhere inside html code just for one element only. I can imagine it could be pretty god damn useful. On the other hand – why not just create another class? Why bother usind if you can just create another extra class and – who knows – maybe use it once again in the futere? Besides – I expect to to look for specific styles in stylesheet, not inside html code, and so do most of webdev’s, aren’t they? I’m affraid it’ll ends up on searching for style declaration in stylesheet while the style will be declared somewhere inside html code.

  • Mark says:

    I agree with others… adding a class, id, or even an inline style is easier. I can’t see what the difference really is. Another option is using a child selector, in some situations.

  • Benjamin Knight says:

    The difference between this and using a class is that you might not be able to assign the scoped element a new class name or id and then prepend every CSS selector with it. Rather you could take any old stylesheet with generic selectors and apply it to that element’s scope only. Yeah?

  • Dan says:

    If you can screw up the page design/layout with this, it’s not worth it. Simple as that. If you need scoped styles, use selectors appropriately. Content authors must not mess with my carefully crafted styles. That way leads to nightmares.

  • thinsoldier says:

    Is there any work being done to bring this same concept directly into .css files also?

    I’m sure a lot of use would rather write styles like this in many situations:


    @scoped #wordpress_generated_really_long_id.generated_class.jquery_plugin_class #content #main ul
    {
    li.first { ...styles... }
    li.last { ...styles... }
    li { ...styles... }
    li.a { ...styles... }
    li.a:hover { ...styles... }
    li.a span { ...styles... }
    li.span { ...styles... }
    }

    rather than what we really have to write today.

  • thinsoldier says:

    Mark says: “adding a class, id, or even an inline style is easier.”

    You can’t style :hover with an inline style

    You don’t always have permission to access to the template or main .css files to add the class/id and new styles for them.

  • Algy Taylor says:

    Wouldn’t it make more sense to have ‘scoped’ as a global attribute? So you’d have:

    <div scoped>
    <style type="text/css"> * { font-size: 97em; } </style>
    </div>

    Making content inside the DIV tag self-contained. To me, that would make more sense in terms of content syndication, comments forms like these and soforth.

    I say content – CSS is the obvious one … but if anyone saw the great big can of worms and fancied opening it, scoped JavaScript (ie JS inside would not be able to access elements outside) would be possible. Or anything else that I haven’t thought of, or doesn’t exist yet but might do in the future!

  • Algy Taylor says:

    @thinsoldier – that sort of change to the CSS would mean the CSS would only work in browsers that implemented that scoping change (ie the site may break in older versions of IE, Firefox, etc).

    Remember the gospel of Saint Berners-Lee – hardware/software ambivalence is a virtue :)

  • Algy Taylor says:

    @thinsoldier – that sort of change to the CSS would mean the CSS would only work in browsers that implemented that scoping change (ie the site may break in older versions of IE, Firefox, etc).

    Remember the gospel of Saint Berners-Lee – hardware/software indifference is a virtue :)

  • Konstantin Vayner says:

    @Algy Taylor:

    This is irrelevant. Browsers that don’t implement the “scoped” attribute as it is defined now, will also render page badly

  • Menelik williams says:

    ‘sabit pants really! I never use inline styles unless ABSULUTELY LIFE TRHEATENINGLY NECASSARY! And this isnt a far cry from them… I do however see a very tiny use for this scope but certainly not to simply code nor provide any viable aid to difficult situations. As for the compatibility i’m sure it will be very on all majors soon … (had to end with something positive)

    Ps @stephanie hodgson could you not just use display inline-block to solve your width issue or a simple js block of code to sniff out the image width of each block to get the widths? Just a blind suggestion of course…

  • This “solution”, as well as the @scoped alternative suggested above are both, essentially, ways of implementing nested selectors.

    Why not just allow nested selectors? Those of you who hate the idea can avoid using them.

    Now, as others have mentioned, this may be a boon to CMS creators, so they can allow portions of the page be styled (potentially by the end user) independent of an outer theme without resorting to inline styles. If this does go forward, I would propose also adding a “src” attribute to the style tag (which seems way more logical than a link tag to me anyway), so that it’s easier to hide scoped styles from old browser.

  • Great article Jack.

    Why not just add a class?
    Why not use ID ?

  • Thiago says:

    Why Opera 9 when the latest stable version is 11.51? It doesn’t make any changes to the article itself (Operra 11.51 and 12 alpha don’t support the scoped attribute yet), but it does a bad impression. ;-)

  • PM5544 says:

    @ John I’m really sorry to hear that you would do anything to keep this from getting implemented, especially since I think it is an improvement to the status quo.

    This reason for this is that I believe this opens the door for HTML mashups and syndicated HTML WITH styling.
    And it will make many use-cases in which people tend to use !important obsolete and thus it will happen less, and that’s a really good thing.
    !important is meant to be used in user-stylesheets to override background-color and font-size and such for visually impaired people, not to win a specificity war with the CSS from the main page.

    In the current state of HTML you would sooner or later be “forced” to use !important to be sure to override the styles of the HTML the content is injected in.
    I think it’s a good thing for a person to be able to style its syndicated content without being forced to brutally override the CSS selectors specificity and use other hacks like styles attributes on the HTML nodes itself or injecting stylesheets in the head with JavaScript or something like that.

    The argument that you should separate content and styling is indeed very important but in this specific use-case it is of less value imho.
    I even think that this is a step INTO that direction because now styling of syndicated content is mostly done in the style attribute on the node itself.

  • PM5544 says:

    btw, when discussing the polyfill i wrote in the weekend for <style scoped> with one of my colleagues, he asked me if the spec was specific on how it should be implemented specificity wise…

    We are pretty curious because there are 2 options:

    The scoped style overrides all the styles from the main page as if the specificity of the node the is in is added to all the style rules therein. so when syndicated the styles defined will always override.

    Or:
    There is no specificity added to the style rules inside the scoped style and therefore creating the situation in which you would still get a specificity battle between the content that is scoped and the main page.
    Like a #id h1{} rule in the main CSS will override a style rule h1{} in the scoped style because it is more specific.

    I interpreted it as the first option because it is the most logical to me in combination with syndicated content (which I think is the main use case for this) but the spec is kinda vague on that subject.
    It only states that style rules in the scoped style shouldn’t “leak” into the rest os the DOM, but says nothing about specificity differences between the scoped and the normal content.

    Does anyone have any thoughts on the subject or knows anything more about this?

    PM5544…

  • Alohci says:

    @PM5544 -That’s a really good question. While I agree that option 1 may be more useful, in the absence of any statement in the spec, I would expect that the specificity rules are not affected and that option 2 is the one that applies.

    I couldn’t find anything in the HTML5 bugzilla for this. It may be worth raising a bug asking for a clarification to be added to the spec.

  • John Allsopp says:

    If that is the problem we are trying to solve, then I think rather than throwing out an ad hoc solution, the problem needs to be really well researched and tested, and then a solution that addresses all the challenges should be developed.

    Mixing arbitrary HTML/CSS/JS in a single document in an ad hoc way is a really serious security challenge, that is not remotely addressed by this.

    I think the shadow DOM problem is closely associated with this, and should be addressed, and the outcomes from that can help here.

    john

  • PM5544 says:

    @John absolutely true, I totally agree that this is not something i would advise people to start doing in every place they want a style to be “sandboxed”, there are other ways of doing so if you’re in control over all your HTML.

    But this is no new situation everybody is able to mix styles and scripts on nodes now with DOM level 0 and the style attributes on HTML nodes.
    And what about iframes? they’re the thing thats used right now to be able to really sandbox styling and behavior, like Facbooks like button, I think everybody knows that thats not only a security threat but also a privacy threat, sending all the pages you visit to the servers of facebook. basically handing them everything you do on the web (not that no one is already handing them every little bit of info now… *sigh*). And they can maintain the content of that iframe even always.

    This might just be a thing that makes those things less desirable to use because it makes it that much more maintainable and faster to render.
    I would be very interested in hearing what you think what will solve the problems which arise when closely mixing behavior and styling.

    My point is, mashups and syndicating happens and it will only happen more in the future, why not hand developers a better way of doing so, even if it is in baby steps to evolutionize instead of revolutionize?

    PM5544…

  • PM5544 says:

    @ Alohci I searched the mailing list yesterday as well but didn’t find anything that could clarify this, I think filing a bug is a bit too much, maybe there’s some place I can just ask? any ideas?

  • Alohci says:

    @PM5544 – I think filing a bug is the proper thing to do, given that others will probably also want an answer to the question, but if you want to just ask, try the #whatwg IRC channel: irc://irc.freenode.net/whatwg

  • PM5544 says:

    @Alohci ah right, good point. I’ll try filing a bug.

  • Missy says:

    I first read this post last week; I’ve only just stopped hyperventilating about it.

    It’s taken years for separation of style and content to become a standard practice, and the web is an infinitely better place for it.

    We really don’t need this ill-considered feature in the new spec, IMO.

  • Mike says:

    Wow.

    Clearly none of the readers of this site have ever developed for the Enterprise – specifically portlet containers such as JBoss, Liferay, etc. These rely on pulling in third party code in a dashboard-style UI. Think NetVibes (or PageFlakes for those who remember it). In fact it would also apply in those cases. The point being you absolutely cannot tell what
    (a) your containing ID will be
    (b) what other classes are used on the page or
    (c) what other styles you might need to override for your own UI.

    This scope attribute would solve most if not all of those issues in one fell swoop.

  • Just as others think, this is just another step to inline styling, which we must stay away from. ONLY and ONLY were this useful is if you host a site with user-generated content and allow them to modify the look as the user sees fit.

    How that note, you’d have to be care that they don’t screw up the rest of the website styles. Here’s a bug i found just using the current article example:

    As described, the scoped style should apply to the immediate parent “” and all childs within the parent.


    <style scoped>
    p { color: red; }
    </style>

    … though changing the scoped styling above to this (below) will apply outside the parent element.


    <style scoped>
    h1, h2 { color: red; }
    </style>

    … try it yourself: http://jsbin.com/ozerih/22/edit

  • Chris says:

    Honestly, I feel just adding a class to the parent element and styling accordingly is appropriate enough. Let CSS handle it.

  • Theo says:

    Well a lot ado about nothing if you ask me.. this will never be the way I would like to style specific parts of a page.

  • This is great news for AJAX developers/designers. Now one can return little chunks of HTML + CSS from the server without having to:

    1. Pull in a global CSS file that already contains the style but might not be used if the AJAX request isn’t fired.
    2. Embed the styles in the traditional style=”foo: bar” syntax in the returned AJAX content.
    3. Request a separate CSS file with a loader. (Like YepNope)…

    Awesome, and look forward to this functionality.

  • Paul Irish says:

    It’s in Chrome canary now. about:flags to enable it.

  • Stephanie Hobson says:

    Thanks for the update Paul. I have to go play now :)

    Also, plus one for Mike’s and Jordan’s comments which parallel the environment I’m working in. Glad to see I’m not the only one!

  • Agreed with Stephanie et al. As soon as you realize that you don’t get to design a page, but only fragments of a page that will get assembled, this becomes hugely important. User-generated content and user-submitted styles that you want to apply only to their own content is another valid use case. Yes, I have personally run into both many many times.

    Now, perhaps this isn’t the ideal solution. But it’s at least trying to address a very real problem, which is that pages are no longer a single entity but increasingly a series of fragments stitched together, each with their own style and behavior needs, many of which won’t even be known when the DOM is first built in the browser. HTML today sucks at that use case, and the alternatives are iframes and insane custom AHAH-bypassing screwiness that is always backend-platform-specific.

    If this approach isn’t sufficient, let’s discuss other alternatives that would be better. But it is a problem space that needs solving.

  • Jami Intal says:

    In the WP themes I develop, my pages usually include mid-document styles for modifying styles in small areas of the design depending on the user’s taste. Those style snippets simply target the elements by class names (randomly generated class names in most instances).

    The scoped attribute would actually help for my case, but I think the attribute should just be left as an optional attribute. Validator.w3.org shows ‘scoped’ as mandatory and throws off an error. I find it uncomfortable that even though I have technically scoped the style properly with just plain ol’ code discipline, I would be forced to use the attribute just to conform to the validation.

  • DanMan says:

    Wouldn’t it be better if you defined a “scopedcss” attribute on the parent element? Like creating a sandbox for users to add their own styles, whatever they may be, without having to worry about it affecting the rest of the page?

  • Clemens Kaposi says:

    Take, for example, Stu Nicholls’ CSS only tabbed pages with persist and other features. Imagine you implemented a server-side script that generated theses tabs per-request.

    If you don’t know in advance how many tabs, or even multiple such tabbed widgets, will end up on the page, it is much more feasible to use a scoped style element and generate the corresponding CSS (with the also dynamically generated targets’ IDs) on the fly.

  • Daniel says:

    Firefox Nightly builds now also support it. (Feature enabled out-of-the box)

    Another hint on the spec, would be to further emulate &ltlink /&gt by putting
    &ltstyle scoped&gt@import(url);&lt/style&gt
    before all other scoped styles. That way, the priority of styles over links is preserved.

    I intend to use this attribute in an editor similar to jsfiddle. Let me know what you think.

  • Would it not be wiser to have <style> scoped by default? I can only see this being relevant for adding third party code to your page, and it would be useful if that was constrained to a scope in that case. Although I don’t like the idea of mixing presentation and content, it seems more useful to have a “global” attribute instead — so you can use <style global> if you really wanted it for some reason. It would also be more backwards-compatible.

  • Ken Newman says:

    I don’t much care for dogma surrounding the separations of concerns. As a general rule, in most cases, you should keep stuff separated…unless there is a compelling case not to. I encounter many such cases during my work, and think that putting styles inline, or embedded, are completely valid (doing so is only a problem when it’s ill-considered). It’s absurd to suggest that it never right to do so, or that it’s only an “edge case.” The scoped attribute is a brilliant feature. Syndicated content (article elements) and widgets seem obvious cases for it. When you “scope” with an id attr, you open it up for potential conflict.

  • Jason says:

    In my opinion I believe this started to come about people people are so used to writing JavaScript files inline while not using ‘inline’ but instead wanted styles to be pretty on multiple lines. If you think that inline styles are bad this would be just as bad.

    In terms of specificity does this render itself with the same precedence as a typical inline style? Couldn’t you just write your styles to a php specific CSS file by reading the file and writing to it?

  • Jason says:

    I also don’t believe any sane web developer should use this unless they are are only interested in experimentation. The scope attribute is not crossbrowser compatible so if you use for example WordPresses Revolution Slider you run into the major problem of having a broken slider for different browsers at different resolutions. I think I would rather take the error from W3C than add the scoped attribute.

  • I think it’s great though was a mess when css mingle so much in html :)

  • Edwin says:

    And, it’s gone from the “blink” codebase:

    http://src.chromium.org/viewvc/blink?view=revision&revision=175720

  • Rasael says:

    Probably in a production environment is not the best choice to go, especially for the compatibility issues but there are many use cases that made this attribute really useful!

    In the project I’m working on there is almost 1MB of css that is generated and managed by an external company.

    Therefore using the scoped attribute allows us to fix layout errors directly and propose a solution before the next release of the css. Without this element we should learn all css classes or have to wait for an answer and implementation and it could take days..

    Therefore I’m in with this attribute, even better if its brought to a custom tag as Lazaris proposed and then, if used in the right way, it could only give benefits.

  • Carl says:

    Why not do it via CSS and use something similar to @media like @this or @scoped, or if it needs to be in the style tag use media=’scoped’ rather than blank or media=’all’. That should make it un-rendered by older browsers and newer browsers can make things pretty as needed!

    Or maybe treat it like the Shadow DOM? If you really need to style something that much that can’t be done with a few extra classes or IDs then that might be a better way to achieve an isolated block of styled HTML. Kinda like a iFrame but more integrated.

  • Evert says:

    I guess this ‘scoped’ business was introduced with web components in mind (styles inside a template are supposed to be scoped).
    But I don’t like the idea one bit. (I don’t like the idea about web components. The basic thought behind it is great, but the implementation is horrible imho).

    Anyway, I never understood why stylesheets are loaded using a link-element. So in order to prevent overused inline styles as well as promote backward compatibility, why not implement:

    <style src='url' scoped='id-of-element' exclude-root=true|false>

    This way you can target a specific part of the html through the scoped-attribute and with the exclude-root-attribute you can exclude these styles from other parts of the page.

  • Evert says:

    Forgot: And older browsers will ignore this script-element as they do not understand the src-attribute on it.

  • Leave a Reply to Shelley

    Some HTML is ok

    You can use these tags:
    <a href="" title="">
    <abbr title="">
    <b>
    <blockquote cite="">
    <cite>
    <del datetime="">
    <em>
    <i>
    <q cite="">
    <strong>

    You can also use <code>, and remember to use &lt; and &gt; for brackets.