HTML - Style (Element|Embedded Style) - Attribute

About

Style in HTML is:

that permit to declare a style.

Type

Element

The style element allows style information to be embedded in documents.

<style>
.green {
     color: green; 
     background:transparent;
}
.blue {
     color: blue; 
     background:transparent;
}
</style>
<p>My sweat suit is <span class="green">green</span> 
and my eyes are <span class="blue">blue</span>.</p>

Style Location

An style element should be inside metadata element and is usually part of the head.

Style in Body

Style in a body element is accepted by browser but this is not the standard. The HMTL DTD does not allow it.

But all browsers support it. Mainly because there is no other way to add styling to a fragment of HTML added via an Ajax request.

style in body has the consequences to re-paint the page and may then cause flash of unstyled content (FOUC).

Attribute

The style content attribute is a global CSS styling attribute.

Example: the words that refer to colors are marked up using the span element and the style attribute.

  • Html example:
<p>My sweat suit is <span style="color: green; background:transparent">green</span> 
and my eyes are <span style="color: blue;background: transparent">blue</span></p>
<p>My sweat style was <span>this color</span>
  • Javascript
let firstSpan = document.getElementsByTagName("span")[0];
console.log("The color of the first span is "+firstSpan.style.color);

// Inline color copy
let thirdSpan = document.getElementsByTagName("span")[2];
thirdSpan.style.cssText = firstSpan.style.cssText;

Using the style attribute to hide and show content, or to convey meaning that is otherwise not included in the document, is non-conforming. (To hide and show content, use the hidden attribute.)

Documentation / Reference


Powered by ComboStrap