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.
<head> <meta charset="utf-8"> <title>The Style Keyword</title> <style> body { color: red; } </style> </head>
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:
<div> <style scoped> p { color: red; } </style> <p>this sibling element is red</p> <div> <p>this cousin element is red</p> </div> </div>
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.
<div> <p>this is NOT red</p> <style scoped> p { color: red; } </style> <div> <p>this is red</p> </div> <p>this is red</p> </div>
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.