Sub topic 3
Inline styles: the style attribute
This chapter covers the style attribute: its syntax, where it works well, where it causes problems, and how it interacts with other styling methods. It assumes you can write basic HTML (elements, attributes, the head and body structure) and that you know what a CSS rule looks like. You should be able to save a text file and open it in a browser.
What an inline style is
An inline style is a set of CSS declarations written in the style attribute of a single HTML element. The browser applies those declarations to that element and to nothing else.
<p style="color: crimson; font-weight: bold;">This paragraph is styled inline.</p>The attribute value is not a full CSS rule. It has no selector and no curly braces. The element that carries the attribute is the target, so the selector is implied. What you write is only the declaration list.
Syntax of the attribute value
The value is a list of declarations. Each declaration is a property, a colon, and a value. Semicolons separate declarations.
<p style="color: darkblue; background-color: lightyellow; padding: 0.5rem;">
Three declarations on one element.
</p>A few rules cover most mistakes:
- The last semicolon is optional, but keeping it makes later edits safer. If you add a declaration after a missing semicolon, the two run together and both can break.
- Property names are written in CSS form, with hyphens:
background-color, notbackgroundColor. - The attribute value is delimited by quotes. If a CSS value needs quotes, use the other kind:
style="font-family: 'Courier New', monospace;". - Whitespace and line breaks inside the value are ignored, so long lists can be split across lines.
- An invalid declaration is dropped and the browser keeps reading. A typo in one property does not cancel the others.
What you cannot do in the attribute
Because the attribute contains only declarations, some CSS features are not available:
- Selectors of any kind, including pseudo-classes such as
:hoverand pseudo-elements such as::before. - At-rules, including
@media,@font-face, and@keyframes. - Reusing one set of declarations on several elements.
This is the most important limit. You cannot make a link change color on hover with an inline style, and you cannot change a layout at a narrow screen width. Those need an internal or external stylesheet.
Example: a small page with inline styles
Here is a complete page that uses only inline styles.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Inline styles</title>
</head>
<body style="font-family: system-ui, sans-serif; margin: 2rem;">
<h1 style="color: navy;">Release notes</h1>
<p style="color: crimson; font-weight: bold;">Breaking change in version 2.</p>
<p style="color: crimson; font-weight: bold;">Breaking change in version 3.</p>
<p>This paragraph has no style attribute, so it uses browser defaults plus anything inherited from body.</p>
</body>
</html>Three things happen here:
- The
bodyelement carries afont-family. Many properties, includingfont-familyandcolor, are inherited, so the paragraphs and heading use that font even though they have no style attribute of their own. - The
marginonbodyis not inherited. It affects only the body box. - The two "Breaking change" paragraphs repeat the same declarations. If you wanted to change the color, you would edit each one. That repetition is the main maintenance cost of inline styles.
How the inline style fits the cascade
When the same property is set on one element by more than one source, the browser has to pick one value. That process is the cascade. Inline declarations take part in it like any other source, but they rank high.
A declaration in a style attribute beats declarations from selector-based rules in a style element or a linked stylesheet, even if those rules have higher specificity. Source order does not matter for this comparison. The inline declaration wins whether the stylesheet comes before or after the element.
<head>
<link rel="stylesheet" href="site.css">
<style>
p { color: blue; }
</style>
</head>
<body>
<p>Blue, if site.css sets p to another color, because the style element comes later and has equal specificity.</p>
<p style="color: red;">Red, because the inline declaration beats the selector rules above.</p>
</body>The first paragraph is decided by source order: the style element comes after the link, and both rules have equal specificity. The second paragraph is decided by the inline style, which beats both.
The diagram is a simplification. It leaves out browser default styles, user styles, and cascade layers, and it shows only the question that matters for this chapter: where the inline style sits. The next chapters on the cascade and specificity cover the full ordering.
The `!important` exception
A stylesheet rule that uses !important beats a normal inline declaration.
<style>
p { color: green !important; }
</style>
<p style="color: red;">This text is green.</p>An inline declaration that is also marked !important beats the stylesheet one. Using !important in this way is a sign of a styling system that has become hard to reason about. It is better to avoid the conflict than to win it.
Common uses
Inline styles are worth using in a limited set of situations.
- A one-off adjustment. A single element needs a tweak that no other element will share.
- Values computed at run time. A script or a server template sets a value per element, such as a progress bar width or a user-chosen color.
- Quick experiments. You want to see an effect before moving the rule into a stylesheet.
- HTML email. Many email clients ignore or strip
styleelements and linked files, so inline declarations are the reliable option there. Email tooling often generates them from a stylesheet automatically. - Passing a value to a stylesheet. An inline custom property (see below) lets a stylesheet use a per-element value without per-element rules.
Setting styles from JavaScript
Scripts can read and write inline styles through the element's style property. This property maps to the attribute, and it uses camelCase names.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Progress</title>
</head>
<body>
<div id="bar" style="background: seagreen; height: 1rem; width: 0;"></div>
<script>
const bar = document.getElementById("bar");
bar.style.width = "60%";
console.log(bar.style.backgroundColor);
</script>
</body>
</html>The script changes width from 0 to 60%. The console.log call prints seagreen. Two details matter:
element.stylereflects only the inline declarations. It does not report styles that come from stylesheets. To read the final computed value, usegetComputedStyle(element).- The camelCase name
backgroundColorcorresponds to the CSS propertybackground-color.
Passing values with custom properties
A custom property is a name that starts with two hyphens and holds a value you choose. You can set one inline and read it in a stylesheet with var().
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Custom property</title>
<style>
.meter {
width: calc(var(--percent) * 1%);
height: 1rem;
background: steelblue;
}
</style>
</head>
<body>
<div class="meter" style="--percent: 35;"></div>
<div class="meter" style="--percent: 80;"></div>
</body>
</html>The inline attribute carries only the data. The presentation rules stay in the stylesheet. This keeps the benefits of reuse while allowing per-element values.
Drawbacks
Inline styles have costs that grow with the size of a project.
| Concern | Effect of inline styles |
|---|---|
| Reuse | Declarations are repeated on every element that needs them. |
| Maintenance | A design change means editing many places in the HTML. |
| Separation of concerns | Content and presentation are mixed in one file. |
| Caching | Inline styles travel inside the HTML, so the browser cannot cache them separately from the page. |
| Selectors and media | Pseudo-classes, pseudo-elements, and `@media` are not available. |
| Overriding | Stylesheets cannot override them without `!important`, which makes later changes harder. |
| Content Security Policy | Blocked by strict policies unless they are explicitly allowed. |
Overriding is the hidden cost
The high rank of inline styles causes the most trouble over time. Suppose a template sets style="color: red;" on many elements, and later you add a dark theme. A theme stylesheet that sets color for those elements has no effect, because the inline declaration wins. The only stylesheet-side fix is !important, which then needs to be used again for every later override. Moving the declaration into a class avoids the problem.
Inline styles and Content Security Policy
A Content Security Policy (CSP) is an HTTP response header that tells the browser which sources of content it may use. The style-src directive controls styles.
Content-Security-Policy: style-src 'self'With this header, the browser accepts stylesheets loaded from the same origin. It blocks style attributes and style elements, because those count as inline styles. The affected declarations are ignored, and the browser reports a violation in the console.
Sites that need inline styles under a CSP have two main options:
- Allow them with
'unsafe-inline'. This works but removes much of the protection. - Allow specific
styleelements with a nonce or hash. This does not coverstyleattributes unless the policy also uses'unsafe-hashes'with matching hashes, which is more involved.
Setting element.style.property from JavaScript is treated differently from the markup attribute. In current browsers, changes made through the CSSOM (the object model for styles), such as element.style.width = "60%", are generally allowed under a strict style-src, while setting the attribute text with setAttribute("style", ...) is blocked. Check the behavior in the browsers you support.
If you expect to deploy under a strict CSP, avoid inline style attributes from the start. Use classes, and use custom properties set through the CSSOM where per-element values are needed.
Debugging inline styles
Browser developer tools show inline styles in the Styles pane for the selected element. They appear at the top as element.style { ... }, above the rules from stylesheets. Rules that lost the cascade are shown with a line through them. You can edit the inline declarations live to test changes. The detail of this workflow is covered in a later chapter.
If an inline style seems to have no effect, check these causes in order:
- The property name or value has a typo. Invalid declarations are dropped silently, and the tools show them with a warning mark.
- The attribute value has an unclosed quote, which can swallow the rest of the tag.
- A stylesheet rule with
!importantis overriding it. - A CSP is blocking inline styles. Look for a violation message in the console.
- The property does not apply to that element, for example
widthon an inlinespan.
Summary of when to use it
Use the style attribute for values that are truly specific to one element or computed at run time, and for HTML email. For anything shared, or for anything that needs hover states, media queries, or theming, use a style element or a linked stylesheet. The following chapters cover those two methods.
Exercise
A page has the rule p { color: blue !important; } in a linked stylesheet and the element <p style="color: red;">Text</p>. What color is the text, and what would you change to make the paragraph red without adding !important to the inline style?
Show answer
The text is blue, because a stylesheet declaration marked !important beats a normal inline declaration. To make it red without more !important, remove !important from the stylesheet rule (the inline declaration then wins), or better, remove the broad p rule and style paragraphs through a class.
Exercise
Under the header Content-Security-Policy: style-src 'self', what happens to <p style="color: red;"> and to a <style> element in the page head, and which two approaches let a site keep styles under this policy?
Show answer
Both are blocked, because they count as inline styles and the browser ignores them and logs a violation. The site can move the rules into a linked stylesheet from the same origin, or loosen the policy (for example with 'unsafe-inline', or a nonce or hash for style elements), though loosening reduces protection.