Pragmateek Pragmateek - 2 years ago 157
HTML Question

Declare CSS style outside the "HEAD" element of an "HTML" page?

my use-case is the following :

I'm composing an HTML page by using parts that are valid HTML fragments but not valid pages,
like Divs; these elements are using CSS to manage their style.

I'd like to allow each fragment to be responsible for its own styling requirements and to not rely on the declarations of style-sheets in the main fragment (the one with the "HTML" tag).

So here come the question : is there any (standard) way to add some CSS styling outside the HEAD element (excluding the inline styling via the "style" attribute) ?

I guess I could use frames but I'd prefer to avoid this solution.

Thanks in advance for your help.


Thanks to the propositions of zzzzBov, JMC Creative and moontear, and after some testing, here is the answer :

  • use JavaScript to dynamically load some CSS style-sheets : HTML4/XHTML and HTML5 compliant,

  • embed "style" elements directly inside the fragments : non-compliant with HTML4/XHTML but seems to be broadly supported, and is HTML5 compliant.

As I must support email clients I've used the second solution which moreover is more simple.

Thanks all for your interest and participation.

Answer Source

HTML5 allows you to scope the style element to belong to the style's parent node and children. (check out the scoped attribute).

I don't know how well supported it is as of yet. At least being a part of the HTML5 spec, it's likely to get much better support within the next couple years.

An example of how you would use it:

<div class="chunk">
  <style type="text/css" scoped>
      text-decoration: underline;
  <p>lorem ipsum dolor sit amet</p>

Just make sure you use the html5 doctype <!DOCTYPE HTML>.

Update / Warning -- currently (May 2016) reports that Firefox is the only browser that supports scoped CSS styles. Support was removed from Chrome around v36/37.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download