Home >Web Front-end >CSS Tutorial >How Can JavaScript Dynamically Add CSS Styles to a Web Page?
Adding CSS Styles Dynamically with JavaScript
The ability to dynamically add CSS rules via JavaScript is a powerful technique for modifying the visual appearance of a web page on the fly. One common approach is creating a new style element and appending it to the document head.
// Your CSS as text var styles = ` .qwebirc-qui .ircwindow div { font-family: Georgia,Cambria,"Times New Roman",Times,serif; margin: 26px auto 0 auto; max-width: 650px; } .qwebirc-qui .lines { font-size: 18px; line-height: 1.58; letter-spacing: -.004em; } .qwebirc-qui .nicklist a { margin: 6px; } ` var styleSheet = document.createElement("style") styleSheet.textContent = styles document.head.appendChild(styleSheet)
This code creates a new style element and sets its text content to the provided CSS styles. Next, it appends the style element to the head of the document, which ensures that the styles are applied immediately.
The above is the detailed content of How Can JavaScript Dynamically Add CSS Styles to a Web Page?. For more information, please follow other related articles on the PHP Chinese website!