Free HTML tutorial

HTML Styles: Add CSS to Elements

HTML provides structure and CSS controls presentation. Learn what the style attribute does, how to write a declaration, and when a separate stylesheet is easier to maintain.

Quick answer: The HTML style attribute applies CSS declarations directly to one element. It is handy for a small test or demonstration, while a stylesheet is usually clearer when styles need to be reused or changed.

Write an inline style

Put the style attribute in an element’s opening tag. The value contains CSS property and value pairs, separated by semicolons.

<p style="color: #26384a; background-color: #f1f5f9;">
  This paragraph has inline CSS.
</p>

Here, color sets the text color and background-color sets the background. Each declaration ends with a semicolon so the next declaration is easy to separate.

Use a stylesheet for shared design

When several elements need the same appearance, give them a class and define the rules once in a CSS file. Link that file from the document head.

<head>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <p class="notice">This paragraph uses a reusable class.</p>
</body>
.notice {
  color: #26384a;
  background-color: #f1f5f9;
}

Now the same .notice rule can style multiple elements. A separate file also keeps content and presentation easier to review, update and reuse across pages.

When inline styles are a poor fit

Repeated style attributes can make a document harder to maintain and override. They also cannot contain selectors, pseudo-classes or media queries. Use a stylesheet when you need responsive layouts, hover and focus states, or a consistent site-wide design.

Keep meaning in the HTML. A color or font should not be the only way that important information is communicated.

HTML style questions

Is the style attribute HTML or CSS?

The attribute is part of HTML markup, and its value contains CSS declarations. It applies those declarations to the element where the attribute appears.

Should I use a style attribute on every element?

No. Inline styles are useful for limited examples or quick checks, but shared styles are easier to manage in a stylesheet with classes.

Practice: convert repeated styles into a class

Add the same inline color and background to two paragraphs. Then move the declarations into a .notice rule in a stylesheet and apply that class to both paragraphs. Change the color once and confirm that both update.

For details about the attribute, read MDN’s HTML style reference. Continue to HTML and CSS basics to learn more about connecting structure with presentation.