Inline CSS

Inline CSS adds CSS declarations directly to an HTML element using the style attribute. The styles apply directly to the element containing the attribute.

Inline CSS can be useful when an individual element needs a specific style, but it is generally less convenient for styling multiple elements or maintaining the design of an entire website.

The style Attribute

Inline CSS is written as the value of the HTML style attribute. The value contains one or more CSS declarations.

<h1 style="color: blue;">Learning Inline CSS</h1>

In this example, color is the CSS property and blue is its value. The declaration changes the text color of that specific <h1> element.

Unlike internal and external CSS rules, inline CSS does not use a selector because the style attribute is already attached directly to the element being styled.

Multiple CSS Declarations

The style attribute can contain multiple CSS declarations. Each declaration is separated by a semicolon.

<p style="color: #333333; font-size: 18px; line-height: 1.5;">This paragraph uses inline CSS.</p>

This example changes the paragraph's text color, font size, and line height.

Although several declarations can be placed in a single style attribute, long inline styles can make HTML markup harder to read and maintain.

When to Use Inline CSS

Inline CSS can be useful when a style needs to be applied to one specific element and creating a separate CSS rule is unnecessary.

It can also be useful for testing a CSS declaration quickly or in situations where styles must be placed directly on an element.

For styles that are reused across multiple elements or webpages, internal CSS or an external stylesheet usually provides a cleaner and easier-to-maintain approach.

Inline CSS vs. Internal and External CSS

Inline, internal, and external CSS all use CSS properties and values, but the styles are stored in different places.

Inline CSS is stored in the style attribute of an individual HTML element. Internal CSS is stored inside a <style> element in the HTML document, while external CSS is stored in a separate .css file.

External stylesheets are generally the easiest method to maintain when styles are shared across many pages. Internal CSS can work well for page-specific styles, while inline CSS is best used selectively for individual elements.

Inline CSS Example

The following example applies styles directly to a heading and paragraph using the style attribute.

<h1 style="color: blue;">Inline CSS</h1>
<p style="color: #333333; font-size: 18px;">This paragraph is styled with inline CSS.</p>
Play in Editor

The browser reads the declarations in each style attribute and applies them directly to the element containing the attribute.