Inline CSS is a method of applying CSS directly to an individual HTML element. The CSS properties are written inside the style attribute of the HTML tag, and the styles affect only that specific element.
In this chapter, you will learn what Inline CSS is, its syntax, an example of Inline CSS, and its advantages and disadvantages.
Inline CSS is used to apply styles to a single HTML element. Instead of writing CSS in a <style> tag or an external stylesheet, the CSS properties are written directly inside the style attribute of the HTML element.
Since the style is applied only to the element on which it is written, Inline CSS is generally used for applying unique styles to individual elements or for testing CSS properties. However, it is not recommended for styling large web pages because the CSS code cannot be reused and becomes difficult to maintain.
The following syntax is used to apply Inline CSS to an HTML element.
<html_tag style="property1:value1; property2:value2;">
Content
</html_tag>
In this syntax:
The following example demonstrates how to apply Inline CSS to an HTML element.
<h2 style="color:red;margin-left:40px;">Inline CSS is applied on this heading.</h2> <p>This paragraph is not affected.</p>
Output:
Inline CSS is applied on this heading.
This paragraph is not affected.
Explanation: In this example, the style attribute is applied only to the <h2> element. Therefore, the heading is displayed in red with a left margin of 40 pixels, while the paragraph remains unchanged because no style is applied to it.
Inline CSS allows you to apply multiple CSS properties to the same HTML element. Each property-value pair must be separated by a semicolon (;).
<p style="color: blue; font-size: 20px; font-weight: bold;">
This paragraph uses multiple CSS properties.
</p>
Explanation
In this example:
The style attribute can be used with almost any HTML element, such as headings, paragraphs, buttons, images, tables, and links.
<h3 style="color: green;">Welcome to CSS</h3>
<button style="background-color: orange; color: white; border: none; padding: 10px 20px;">
Click Me
</button>
<a href="#" style="color: red; text-decoration: none;">
Visit Website
</a>
Explanation
In this example:
Inline CSS should be used only when a style is required for a single HTML element.
Common use cases include:
Example
<p>This paragraph uses the default style.</p>
<p style="color: crimson;">
This paragraph has a different text color.
</p>
Explanation
The style attribute affects only the second paragraph. The first paragraph remains unchanged because no inline style is applied.
We request you to subscribe our newsletter for upcoming updates.