Inline CSS
Inline CSS applies CSS directly to an individual HTML element using the style attribute. It is useful for simple examples and individual styles, but it is usually not the best choice when the same styling must be applied to many elements.
Using Inline CSS
Inline CSS is written as the value of the HTML style attribute. The CSS applies only to the element containing that attribute.
<p style="color: blue;">This paragraph is blue.</p>
This paragraph is blue.
In this example, color is the CSS property and blue is its value.
Using Multiple CSS Properties
More than one CSS declaration can be placed inside a style attribute. Separate each declaration with a semicolon.
<p style="color: blue; font-size: 18px; background-color: #f5f5f5;">
This paragraph has several inline styles.
</p>
This paragraph has several inline styles.
The declarations change the paragraph's text color, font size, and background color.
The style Attribute
The style attribute is a global HTML attribute, which means it can be used with most HTML elements.
<h2 style="color: #0088cc;">A Blue Heading</h2>
<p style="font-size: 18px;">A larger paragraph.</p>
The value of the style attribute contains CSS declarations. Unlike a regular CSS rule, an inline style does not include a selector or curly braces because the HTML element itself is already being styled.
When Inline CSS is Useful
Inline CSS can be convenient when you need to apply a small style to one particular element. It is also useful in tutorials because the HTML and the CSS being demonstrated can be seen together in a single line of code.
For example:
<span style="color: red;">Important text</span>
For larger websites, styles that are reused are generally better placed in internal or external CSS.
Limitations of Inline CSS
Inline CSS can become difficult to maintain when the same style is repeated on many elements.
<p style="color: blue;">First paragraph.</p>
<p style="color: blue;">Second paragraph.</p>
<p style="color: blue;">Third paragraph.</p>
If the color later needs to change, each inline style may need to be edited individually.
With internal or external CSS, one CSS rule can style all three paragraphs:
p {
color: blue;
}
This keeps the HTML cleaner and makes repeated styles easier to update.
Summary
Inline CSS is written directly on an HTML element using the style attribute. It can contain one or more CSS declarations and applies directly to that element.
Inline CSS is useful for individual styles and simple examples, but repeated styles are generally easier to manage with internal or external CSS. Next, you will learn how to place CSS rules inside an HTML document using internal CSS.
