Inline styles apply CSS rules directly to individual HTML elements using the style
attribute. While quick for small adjustments, they are generally discouraged for larger projects due to maintainability issues and poor separation of concerns.
Example 1: Basic Inline Style
<p style="color: blue; font-size: 16px;">This text is styled with an inline style.</p>
Explanation This example demonstrates how to apply a color
and font-size
directly to a paragraph element using the style
attribute. Inline styles override external or internal stylesheets for that specific element.
Example 2: Multiple Properties Inline
<div style="background-color: lightgray; padding: 20px; border: 1px solid black;">
<h2>Inline Style Box</h2>
<p>This div has a background, padding, and border applied inline.</p>
</div>
Explanation Here, a div
element is styled with a background color, padding, and a border, showcasing how multiple CSS properties can be defined within a single style
attribute. This is useful for quick visual adjustments.
Example 3: Overriding External Styles with Inline
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: green;
}
</style>
</head>
<body>
<p>This text is green from external style.</p>
<p style="color: red;">This text is red due to inline style.</p>
</body>
</html>
Explanation This example illustrates the cascade order, where an inline style on the second paragraph overrides the color: green;
defined in the internal stylesheet, making the text red. Inline styles have high specificity.
Example 4: Inline Style with !important (Avoid if possible)
<p style="color: purple !important;">This text is purple, even if other styles try to override it.</p>
Explanation While generally discouraged, !important
can be used with inline styles to forcefully apply a declaration, overriding almost any other CSS rule. Use it sparingly to avoid maintenance headaches.
Example 5: Inline Style for JavaScript Interaction
<button onclick="this.style.backgroundColor='yellow';">Click Me</button>
Explanation Inline styles can be dynamically manipulated by JavaScript, as shown here where a button's background color changes upon a click event. This provides immediate visual feedback.
Example 6: Basic Inline Image Styling
<img src="image.jpg" alt="A sample image" style="width: 150px; border-radius: 8px;">
Explanation This example applies a specific width and border-radius to an image element directly. It's a quick way to control the appearance of individual images without needing a separate stylesheet.
Example 7: Inline Styles for Form Elements
<input type="text" placeholder="Enter your name" style="border: 2px solid #ccc; padding: 10px;">
Explanation Here, an input field's border and padding are customized using inline styles. This method allows for immediate visual adjustments to form elements.