About

Style in HTML is:

that permit to declare a style.

Type

Element

The style element 1) 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

See HTML - CSS Style in Body (FOUC)

How to create a style element with Javascript

This step by step shows you how to create dynamically a style element in the head.

  • Create a style element
const style = document.createElement('style');
  • Add the CSS rules as content
style.textContent = 'body { background-color: gray } p { color: white }';
document.querySelector('head').appendChild(style);
  • A little bit of content in the page
<p>Lorem Ipsum</p>
  • Result:

Attribute

The style content attribute is a global CSS styling attribute.

Html Style Attribute

You can set the style in the style attribute

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

<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>
  A cloned style sweat has 
  <span>this color</span>
</p>
<p>
  I may also like an object variation of 
  <span>this color</span>
</p>

Javascript Style Property

You can manipulate the style with javascript programmatically with the style property

Example:

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;

// Object notation where you can set multiple properties at once with an object
// The `minus` should be deleted and the next word should be uppercase
// Example: `background-color` becomes `backgroundColor`
let fourthSpan = document.querySelector("p:nth-child(3) span");
Object.assign(fourthSpan.style, {
  color: 'white',
  backgroundColor: 'grey'
});

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