style attribute
The style attribute applies CSS declarations directly to one HTML element. It is useful for a value that is truly local, but reusable styles usually belong in a class or stylesheet.
What you will learn
- How to write CSS declarations in
style - When inline CSS is appropriate
- Why classes and external stylesheets are easier to maintain
Basic syntax
The value is a list of CSS declarations separated by semicolons. Only the element carrying the attribute is affected.
A local style
<p style="color: firebrick; font-size: 1.25rem;">
This paragraph has local styles.
</p>
Each declaration has a property and a value, such as color: firebrick. Keep the syntax valid and include a semicolon when multiple declarations follow one another.
When to use it
- Setting a value that is calculated for one element, such as a chart position or a custom color.
- Creating a small demonstration while learning or debugging.
- Applying a one-off custom property that a component consumes.
A custom property value
<div class="progress" style="--progress: 72%">
72% complete
</div>
Prefer classes for reusable design
Repeated inline declarations are difficult to update and can make HTML noisy. A class keeps structure in HTML and presentation in CSS, so one rule can serve many elements.
Reusable CSS
<p class="notice">This message is reusable.</p>
.notice {
color: firebrick;
font-size: 1.25rem;
}
Important considerations
- Inline styles have high specificity and can be harder to override.
- They do not support media queries, pseudo-classes, or responsive rules by themselves.
- A strict Content Security Policy may disallow inline styles unless an appropriate policy is configured.
- Do not put user-provided text into a style value without careful validation.