Telerik blogs
How ToT2 Dark_1200x303

In this article, we learn how to dynamically style elements by updating their inline styles. We talk about the relationship between the style attribute and the DOM style property, highlighting that CSS declarations include CSS properties as well as CSS custom properties.

Besides making the user interface look great, styles are used to reduce the cognitive load needed in processing an application’s content and also to provide a good user experience. For instance, we use styles to create content hierarchy, to highlight important information and guide user attention.

Additionally, many applications are interactive and present data fetched from APIs. So we often need to dynamically style UI elements based on user interaction and application data.

There are a couple of options for creating dynamic styles. We can programmatically update an element’s inline styles. Alternatively, we can add (or remove) classes to elements. Each option has its use cases.

This article focuses on dynamically styling elements by updating their inline styles. It is important to get to know the DOM style property and the inline CSS declaration block.

In this article we will cover the following building blocks:

  1. Relationship between the style attribute and the DOM style property.
  2. Differences and similarities between CSS properties and CSS custom properties.

This codepen demonstrates creating dynamic styles using CSS custom properties and is based on this article.

In order to study what comes natively with the browser, we will use vanilla JavaScript and HTML.

HTML style Attribute

The HTML style attribute is used to declare inline styles for an element.

The string assigned to the style attribute contains a CSS declaration block.

<div style="background-color: plum;"
id="color-demo"></div>

The style attribute has the highest specificity. Therefore, in our example, the inline background-color declaration overrides the background-color declaration in the style rule with the id selector:

#color-demo {
  width: 100px; height: 100px;
  background-color: honeydew;
}

DOM style Property

The elements in an HTML document are represented as objects in the Document Object Model (DOM). Most HTML attributes, including the style attribute, become properties of the DOM objects.

The style attribute is a global attribute; therefore, all DOM objects have a style property.

As mentioned earlier, the style attribute is used to declare inline styles, so the style property represents the element’s inline CSS declaration block.

CSS Declaration Block

A CSS declaration block contains CSS declarations which are property and value pairs separated by colons and terminated with semi-colons.

A CSS declaration block can have CSS property declarations, as well as CSS custom property declarations.

For example, the following inline CSS declaration block has a --primary-color CSS custom property declaration and a background-color property declaration:

<div style="
  --primary-color: papayawhip;
  background-color: var(--primary-color);">
</div>

It is not surprising, then, that the style property is an object of type CSSStyleDeclaration.

The CSSStyleDeclaration interface exposes properties and methods for querying and manipulating the inline CSS declaration block.

We can categorize the properties of the style object in to the following three types:

  1. Built-in CSS properties
  2. CSS custom properties declared inline
  3. Properties and methods to query and manipulate the inline CSS declaration block

Let us look at each.

Built-in CSS Properties

CSS properties are the built-in properties provided by the browser. We use CSS properties to style HTML elements.

If we inspect a DOM object, for example a HTMLDivElement, we will see that its style
property has all the built-in CSS properties, from alignContent to zoom.

The property values are empty strings "" until they are assigned a value in the inline CSS declaration block.

For example, declaring an inline style for background-color: peachpuff; sets the colorEl.style.backgroundColor to peachpuff.

const colorEl = document.getElementById('color-demo');
console.log(colorEl.style.backgroundColor); // peachpuff
<div style="background-color: peachpuff"
id="color-demo"></div>

If we declare a style rule with padding: 10px, the colorEl.style.padding will still be an empty string "" since padding is not declared in the inline CSS declaration block.

#color-demo {
padding: 10px;}
const colorEl = document.getElementById('color-demo');
console.log(colorEl.style.padding); // ""

CSS Custom Properties Declared Inline

As we saw earlier, a CSS declaration block can have CSS property declarations as well as CSS custom property declarations.

CSS custom properties are a relatively new feature in CSS that allows application developers to create additional CSS properties.

The two dashes (--) in front of a CSS property name denote a CSS custom property. CSS custom properties are used to define values which we can then access in property declarations using the var() function.

For example, if we want to create a square shape using a div element, we can declare a CSS custom property called --size to hold the width and height of the div. Then access the value in the width and height property declarations:

<div style="--size: 100px;
  width: var(--size);
  height: var(--size);
  background-color: mintcream"
id="color-demo"></div>

The browser will substitute the var(--size) function with the value held in --size property, and set the width and height properties to 100px.

The CSS custom properties declared inline become properties of that element’s style property. We can use the style.getPropertyValue() method to check that a property called --size has indeed been created and has a value of 100px:

const colorEl = document.getElementById('color-demo');
console.log(colorEl.style.getPropertyValue('--size')); // "100px"

Just like built-in CSS properties, CSS custom properties are subject to the cascade and inheritance and can be queried or manipulated at runtime with TypeScript/JavaScript.

Properties and Methods to Query and Manipulate Inline CSS Declaration Block

As mentioned earlier, the style property is an object of type CSSStyleDeclaration which exposes properties and methods that let us dynamically query and manipulate an element’s inline styles.

Please refer to the MDN documentation for a full description of the CSSStyleDeclaration properties and methods.

Below are some of the handy properties and methods:

style.length

Returns the number of property declarations in the element’s inline CSS declaration block.

<div id="color-demo"
  style="--size: 100px;  width: var(--size);
  height: var(--size);
  background-color: blanchedalmond">
</div>
const colorEl = document.getElementById('color-demo');
console.log(colorEl.style.length); // 4

style.setProperty(propertyName, value, priority)

Lets us modify an element’s inline CSS declaration block.

So far in this article we used the style attribute to declare inline styles at development time.

We can create and update inline styles at runtime using the setProperty() method. That is, we can modify existing property declarations or create new declarations.

For example, we can dynamically update the --size CSS custom property value based on user input:

<label for="size">
  <input id="size" type="number" oninput="updateSize(event)">
</label>
<div id="demo"></div>
function updateSize(size) {
  const element = document.getElementById("demo");
  element.style.setProperty("--size", `${size}px`);
}

Note that we need to include the unit (for example, px) as part of the value.

style.getPropertyValue(propertyName)

Returns the property value for the specified property declaration in the inline CSS declaration block.

We need to use getPropertyValue() method to get the CSS custom property values, as we did in the previous section (to get the value of --size).

For built-in CSS properties, we can simply use style.<propertyName> to query or update their value, for example:

function updateSize(size) {
  const element = document.getElementById("demo");
  element.style.width = `${size}px`;  element.style.height = `${size}px`;  console.log(element.style.width);
}

Additionally, as we can see, we could create dynamic styles by updating either CSS properties or CSS custom properties. However, we can reuse the CSS custom property values in multiple declarations, making the code more DRY and easier to maintain.

As a side note, it is important to reiterate that the style attribute sets inline styles and, therefore, the style property methods only query and manipulate the element’s inline style declaration block.

So, the CSS property and CSS Custom property values declared in the stylesheets are not accessible with the element.style.getPropertyValue() method.

To access those values, we can use the getComputedStyle() method.

<div id="demo"></div>
#demo {
  --size: 100px; width: var(--size); height: var(--size); background-color: tomato;}
const element = document.getElementById('demo');
console.log(element.style.getPropertyValue('--size')); // ""

const computedStyle = window.getComputedStyle(element);
console.log(computedStyle.getPropertyValue('--size')); // "100px"

style.removeProperty(propertyName)

Removes the specified property from the inline CSS declaration block and returns the property value before being deleted.

Conclusion

We can use an element’s style property to manipulate its inline styles and create dynamic styles based on user interaction or application data.

The HTML style attribute is represented in the DOM style property. The style property itself is an object that represents the inline CSS declaration block.

A CSS declaration block can have declarations for CSS properties as well as CSS custom properties. CSS properties are used to style elements, while CSS custom properties are a newer CSS feature that let us define custom CSS properties to hold values that can be reused.

Like CSS properties, CSS custom properties are subject to the cascade and inheritance and can be manipulated dynamically.


ashnita-bali
About the Author

Ashnita Bali

Ashnita is a frontend web developer who loves JavaScript and Angular. She is an organizer at GDGReading, a WomenTechmakers Ambassador and a mentor at freeCodeCampReading. Ashnita is passionate about learning and thinks that writing and sharing ideas are great ways of learning. Besides coding, she loves the outdoors and nature.

Related Posts

Comments

Comments are disabled in preview mode.