Dynamic Styling with JavaScript
Learn how to dynamically manipulate CSS styles using JavaScript to create interactive, responsive, and engaging web applications.
What is Dynamic Styling?
Dynamic styling refers to the ability to change the appearance of HTML elements programmatically using JavaScript, rather than relying solely on static CSS.
Methods for Dynamic Styling
1. Using the style property
The most direct way to apply styles to an element.
// Get element
const element = document.getElementById('myElement');
// Apply styles
element.style.color = 'blue';
element.style.backgroundColor = '#f0f0f0';
element.style.fontSize = '20px';
element.style.padding = '10px';
// Using camelCase for CSS properties
element.style.marginTop = '15px';
element.style.zIndex = '10';
2. Using cssText property
Apply multiple styles at once with a CSS string.
const element = document.querySelector('.my-class');
element.style.cssText = 'color: red; background: yellow; padding: 15px; border: 1px solid black;';
3. Using setAttribute method
Set the style attribute directly.
const element = document.getElementById('myDiv');
element.setAttribute('style', 'color: blue; font-weight: bold;');
4. Working with CSS classes
Dynamically add, remove, or toggle CSS classes.
const element = document.getElementById('myElement');
// Add a class
element.classList.add('active', 'highlight');
// Remove a class
element.classList.remove('inactive');
// Toggle a class
element.classList.toggle('hidden');
// Check if element has a class
if (element.classList.contains('special')) {
console.log('Element has special class');
}
// Replace one class with another
element.classList.replace('old-class', 'new-class');
5. Modifying CSS variables (Custom Properties)
Dynamically change CSS custom properties.
:root {
--main-color: blue;
--spacing: 10px;
}
// Get the root element
const root = document.documentElement;
// Change CSS variables
root.style.setProperty('--main-color', 'red');
root.style.setProperty('--spacing', '20px');
// Or modify directly
document.documentElement.style.setProperty('--main-color', 'green');
Practical Examples
Example 1: Theme Switcher
// HTML needed: <button id="themeToggle">Toggle Theme</button>
const themeToggle = document.getElementById('themeToggle');
const root = document.documentElement;
themeToggle.addEventListener('click', () => {
const currentTheme = root.getAttribute('data-theme');
if (currentTheme === 'dark') {
root.setAttribute('data-theme', 'light');
root.style.setProperty('--bg-color', '#ffffff');
root.style.setProperty('--text-color', '#333333');
} else {
root.setAttribute('data-theme', 'dark');
root.style.setProperty('--bg-color', '#333333');
root.style.setProperty('--text-color', '#ffffff');
}
});
Example 2: Responsive Element Sizing
// HTML needed: <div id="resizable">Resize me!</div>
const resizable = document.getElementById('resizable');
let isExpanded = false;
resizable.addEventListener('click', () => {
if (isExpanded) {
resizable.style.width = '100px';
resizable.style.height = '100px';
resizable.style.fontSize = '14px';
} else {
resizable.style.width = '200px';
resizable.style.height = '200px';
resizable.style.fontSize = '18px';
}
isExpanded = !isExpanded;
});
Example 3: Dynamic Form Validation Styling
// HTML needed: <input type="email" id="emailInput">
const emailInput = document.getElementById('emailInput');
emailInput.addEventListener('blur', () => {
const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailInput.value);
if (emailInput.value === '') {
emailInput.style.borderColor = '#ccc';
} else if (isValid) {
emailInput.style.borderColor = 'green';
emailInput.style.boxShadow = '0 0 5px green';
} else {
emailInput.style.borderColor = 'red';
emailInput.style.boxShadow = '0 0 5px red';
}
});
Example 4: Animation with JavaScript
// HTML needed: <div id="animatedBox">Animate me!</div>
const box = document.getElementById('animatedBox');
let position = 0;
function animate() {
if (position < 300) {
position += 5;
box.style.transform = `translateX(${position}px)`;
box.style.opacity = (position / 300).toString();
requestAnimationFrame(animate);
}
}
box.addEventListener('click', animate);
Example 5: Dynamic Grid Layout
// HTML needed: <div id="gridContainer"></div>
const gridContainer = document.getElementById('gridContainer');
const items = 12;
// Create grid items
for (let i = 0; i < items; i++) {
const item = document.createElement('div');
item.className = 'grid-item';
item.textContent = `Item ${i + 1}`;
gridContainer.appendChild(item);
}
// Dynamic grid styling based on window size
function updateGrid() {
if (window.innerWidth < 600) {
gridContainer.style.gridTemplateColumns = 'repeat(2, 1fr)';
} else if (window.innerWidth < 900) {
gridContainer.style.gridTemplateColumns = 'repeat(3, 1fr)';
} else {
gridContainer.style.gridTemplateColumns = 'repeat(4, 1fr)';
}
}
window.addEventListener('resize', updateGrid);
updateGrid(); // Initial call
Best Practices
- Use classes over inline styles when possible for better maintainability
- Cache DOM references to avoid repeated queries
- Use CSS transitions for smooth animations instead of JavaScript
- Consider performance when making frequent style changes
- Use CSS custom properties for theme-related changes
// Good practice: Using classes
function toggleMenu() {
const menu = document.getElementById('menu');
menu.classList.toggle('open');
}
// Better performance: Use requestAnimationFrame for animations
function smoothAnimation() {
let start = null;
function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
// Update styles
element.style.transform = `translateX(${Math.min(progress / 10, 200)}px)`;
if (progress < 2000) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
Dynamic styling with JavaScript opens up endless possibilities for creating interactive and responsive web applications that respond to user actions and changing conditions in real-time.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.