HTML Β· Chapter 8 of 45

HTML Styles

The style attribute lets you apply CSS directly to a single element using inline styling, with the syntax style="property:value;".

While inline styles are quick for testing, best practice is to use external stylesheets or a <style> block in the head, keeping structure (HTML) separate from presentation (CSS).

Syntax
<tagname style="property:value;">

Inline styles

The style attribute applies CSS rules directly to one element. It's convenient for quick demos but hard to maintain at scale.

Internal and external CSS

A <style> tag in <head> applies CSS to the whole page. An external .css file linked with <link> is best for larger, reusable styling.

Example 1 (html)
<p style="color:blue; font-size:20px;">Styled text</p>
Output
Styled text (blue, larger font)

Two CSS declarations are combined in one style attribute, separated by semicolons.

Example 2 (html)
<h1 style="text-align:center; background-color:lightgray;">Centered Heading</h1>
Output
Centered Heading (centered, gray background)

Multiple style properties control alignment and background.

Key points

  • The style attribute holds inline CSS.
  • Syntax is property:value; separated by semicolons.
  • Inline styles override external and internal CSS by default.
  • Prefer external CSS files for maintainability.
πŸ’‘ Note: Avoid excessive inline styling in production sites β€” it makes updates and theming harder.

πŸ“ Quick Quiz

1. Which attribute applies inline CSS?

2. What is the correct syntax inside a style attribute?

3. Why is external CSS generally preferred?