The HTML Style Keyword: The Difference Between Tag and Attribute

Introduction

The style keyword in HTML is special, because it’s both a tag (<style>) and an attribute (<p style="color: red;">). It’s easy to confuse the two, as each represents very different ideas.

The style Tag

When used as a tag and without the scoped attribute (discussed below), it must be included as a child of the <head> element and is the primary method by which to include embedded/internal CSS in a document.

&amp;lt;head&amp;gt;
   &amp;lt;meta charset=&amp;quot;utf-8&amp;quot;&amp;gt;
   &amp;lt;title&amp;gt;The Style Keyword&amp;lt;/title&amp;gt;
   &amp;lt;style&amp;gt;
   body {
      color: red;
   }
   &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;

When used inside the <body> element, the <style> element, a W3C-compliant HTML5 feature introduced in 2012, the scoped attribute is required.

It’s important to note that elements styled using the scoped attribute must follow the <style> element in the DOM tree; that is, the styled elements must at least be siblings (or deeper) of the  <style> element.

For example:

&amp;lt;div&amp;gt;
   &amp;lt;style scoped&amp;gt;
   p {
      color: red;
   }
   &amp;lt;/style&amp;gt;
   &amp;lt;p&amp;gt;this sibling element is red&amp;lt;/p&amp;gt;
   &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;this cousin element is red&amp;lt;/p&amp;gt;
   &amp;lt;/div&amp;gt;

&amp;lt;/div&amp;gt;

The example above correctly styles the foreground color of the paragraphs to red.

In the following example, however, the paragraph proceeding the <style> element won’t be made red because it appears before the scoped <style> element.

&amp;lt;div&amp;gt;
   &amp;lt;p&amp;gt;this is NOT red&amp;lt;/p&amp;gt;
   &amp;lt;style scoped&amp;gt;
   p {
      color: red;
   }
   &amp;lt;/style&amp;gt;
   &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;this is red&amp;lt;/p&amp;gt;
   &amp;lt;/div&amp;gt;
   &amp;lt;p&amp;gt;this is red&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;

The very nature of this method is to intersperse content (HTML) with presentation (CSS), but modern web development has always sought to maintain the separation of these two from each other and from behavior (JavaScript).

For larger websites controlled via a CMS, this method will likely prove to be a valid and compliant HTML5 solution, but for smaller sites not maintained via a CMS, this intermingling of languages will be confusing. Use sparingly.

Leave a Reply

Your email address will not be published. Required fields are marked *