The style Attribute
The style attribute applies CSS declarations directly to one element, which is handy for quick tests or values set by scripts but hard to reuse and maintain compared with a stylesheet.
Compare a one-element style with a reusable stylesheet rule.
HTML handles meaning and CSS handles looks, but there is one attribute that lets you write CSS straight onto an element. It is useful in a few specific situations and a maintenance headache almost everywhere else. Knowing which is which is the whole lesson.
The rule
style styles one element; reuse belongs in a stylesheet.
The style attribute holds CSS declarations: property: value pairs separated by semicolons.
<p style="color: darkgreen; font-weight: bold;">Order confirmed.</p>This is called an inline style. It applies to that one element only.
When it helps:
- A quick experiment while you are figuring out a design.
- A value calculated by a script, such as the width of a progress bar:
<div class="progress-bar" style="width: 64%;"></div>- A one-off value tied to specific content, such as a custom property holding a colour chosen by the user.
Why it hurts elsewhere:
- No reuse. Forty paragraphs with the same inline style means forty edits for one colour change. A class and one stylesheet rule means one edit.
- It wins too easily. Inline styles override normal stylesheet rules, so later designers struggle to change them.
- It mixes layers. Meaning and looks end up tangled in the same file, which makes both harder to read.
The better default is a class on the element and a rule in a stylesheet:
<p class="success">Order confirmed.</p>.success { color: darkgreen; font-weight: bold; }(There are three ways to add CSS: inline, internal and external. You will meet the other two when you study CSS. For now, recognise inline styles and know when they fit.)