How to set CSS styles using JavaScript
In my previous article, we looked at different ways to get style information from an HTML element using JavaScript. Today, you’ll learn how to apply CSS styles to HTML elements with JavaScript.
Let us say we have the following element:
div class="pizza">Hot, spicy, pizza 🍕div>
Now, we want to change its text, background colors, and font style CSS properties using JavaScript. What should we do? There are multiple options available in JavaScript.
The easiest and straightforward way to change the CSS styles of an element with JavaScript is by using the DOM style property. All you need to do is fetch the element from DOM and change its inline styles:
const pizza = document.querySelector('.pizza') // change the text color to white pizza.style.color = 'white' // set background color to blue pizza.style.backgroundColor = 'blue' // change font style to italic pizza.style.fontStyle = 'italic'
The style property uses the camel-case naming conventions for CSS properties and applies styles inline to the element:
div class="pizza" style="color: white; background-color: blue; font-style: italic;">Hot, spicy, pizza 🍕div>
Another way is to create a
const style = document.createElement('style')
Finally, append the style element to the DOM. To do this, get the
tag using document.head , and then call the appendChild() method on it to append the style element:document.head.appendChild(style)
// create an element const style = document.createElement('style') // add CSS styles style.innerHTML = ` .pizza ` // append to DOM document.head.appendChild(style)
The CSS Object Model is a set of APIs allowing the manipulation of CSS from JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify [the] CSS style dynamically.
The CSSStyleSheet.insertRule() method inserts a new CSS rule to a stylesheet. Here is how you can use this method to add styles to the above HTML element:
// create an new style const style = document.createElement('style') // append to DOM document.head.appendChild(style) // insert CSS Rule style.sheet.insertRule(` .pizza `)
It is not really required to create a new element. You can use existing elements as well as external stylesheets to add CSS rules using insertRule() . The insertRule() method works in all modern browsers, including Internet Explorer 9 and higher.
Constructable Stylesheets is a modern way of creating and distributing reusable styles when working with the Shadow DOM. Here is an example that creates a Constructable Stylesheets and appends it to the Shadow DOM:
// create a new shared stylesheet const sheet = new CSSStyleSheet() // add CSS styles sheet.replaceSync(` .pizza `) // apply the stylesheet to a document document.adoptedStyleSheets = [sheet]
In this article, we looked at four ways to add CSS styles to an HTML element in JavaScript. So, which method should you use? It depends on what you want to achieve by dynamically changing the CSS. If you only want to modify CSS styles for a single element, it is better to use the style property. This property changes the inline styles for a specific HTML element without affecting global styles. If you want to apply a style to a set of HTML elements, create a new tag with the necessary CSS properties and append it to the document. Read Next: How to add multiple CSS styles using JavaScript ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
Javascript Set CSS Set CSS styles with javascript
2. Global styles
var style = document.createElement('style'); style.innerHTML = ` #target < color: blueviolet; >`; document.head.appendChild(style);
3. CSSOM insertRule
var style = document.createElement('style'); document.head.appendChild(style); style.sheet.insertRule('#target ');
While it might look similar to the 2nd option, it's definitely different.
As you can see in Chrome devtools, tag is empty, but the style (darkseagreen color) is applied to the element. Also the color can't be changed via devtools because Chrome doesn't allow editing dynamic CSS styles. Actually such behavior was the motivation to write this post. A popular CSS-in-JS library Styled Components use this feature to inject styles in production mode because of performance. This feature might be undesirable in specific projects or environments and some folks complain about it in the project's issues.
4. Constructable Stylesheets (July 2019 update)
// Create our shared stylesheet: const sheet = new CSSStyleSheet(); sheet.replaceSync('#target '); // Apply the stylesheet to a document: document.adoptedStyleSheets = [sheet];
More details are here.
This option is only valid for Chrome, so use with caution. Do you know other options to add styles with javascript? What is your preferred option these days? Thanks for reading!
Setting CSS Styles with JavaScript
Why is there a need to change CSS with Javascript? Let’s discuss a few cases where changing CSS styles in Javascript makes sense.
- To load stylesheets dynamically.
- After an initial page render, sometimes, there will be a need to change a particular style for the element in a page dynamically. In cases like this, writing CSS in Javascript helps.
- If on any webpage some progress is happening and we want to change the look and feel after progress is finished. Here as well, changing styles in Javascript helps.
- Many developers are much more confident in writing Javascript than CSS, for those, it is hard to write and maintain CSS. So they like to write CSS in Javascript. There are libraries that allow to style components with CSS in Javascript like style components.
Above are a few which I can think of, but I am sure there are many.
How to change CSS with Javascript?
There are different ways of setting CSS with Javascript for different scenarios. Below is the list :
- Inline style
- Adding or removing class names from the element
- Global styles
- Adding or replacing stylesheets
- Inserting CSS rules
Let’s discuss each one in detail.
Inline style is the way to add styles directly to elements. The highlighted part of the devtool image below shows how red color and font size got added to the title. Inline styles can also be written directly on an element, but here we will look at how we can achieve the inline style in Javascript.
Adding red color and font size to the title
We have an H1 element with the default styles and with an Id attribute, which has a value ‘title’. Below is the image which shows HTML view, browser view and devtool view of the H1 element.
HTML view, browser view, and devtool view of the H1 element.
Now, will change the font size and color of the H1 element to 50px and red respectively. In CSS we will apply styles on elements ID.