Course contentsShow
← Web Development
Lesson 692 of 2,98212. The Document Object ModelFree lesson

Modifying Inline Styles

Set inline styles directly via element.style property and understand when to use CSS classes instead.

Modifying Inline Styles

What you'll learn: How to change an element's appearance directly through JavaScript using the style property, and when this approach is appropriate.

What Are Inline Styles?

Every DOM element has a style property that lets you set CSS properties directly in JavaScript. This adds inline styles to the element—the same as if you'd written style="color: red" in your HTML.

The Syntax

Access element.style and set CSS properties using camelCase versions of their CSS names:

const box = document.getElementById('myBox');

box.style.backgroundColor = 'blue';    // CSS: background-color
box.style.fontSize = '20px';           // CSS: font-size
box.style.margin = '10px';

Notice how background-color becomes backgroundColor and font-size becomes fontSize. JavaScript uses camelCase because hyphens aren't valid in property names.

When to Use Inline Styles

Inline styles are perfect for dynamic, calculated values:

  • Positioning elements based on user interactions
  • Animations controlled by JavaScript logic
  • Setting dimensions based on calculations
  • One-off style changes that depend on runtime data

When to Use Classes Instead

For most styling needs, use classList methods you learned earlier. Classes are better for:

  • Pre-defined visual states (active, hidden, error)
  • Reusable styles across multiple elements
  • Media queries and responsive design
  • Maintainability and separation of concerns

Think of inline styles as a screwdriver and classes as a power drill—sometimes you need precision control, but usually the more powerful tool is the right choice.

Key Takeaway: Use element.style.propertyName to set inline CSS values with JavaScript when you need dynamic, calculated styling; prefer adding/removing classes for predefined visual states.