Skip to content

HTML Styles

The style attribute allows you to apply CSS styles directly to individual HTML elements. However, using external stylesheets is generally the preferred method for styling web pages.

By default, HTML elements have basic styling provided by the browser (e.g., black text, white background, standard font sizes for headings).

You can override these defaults using CSS (Cascading Style Sheets). One way to apply CSS is using the style attribute directly on an element.

This example uses the style attribute to change the background color of the <body> element:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Inline Style Example</title>
</head>
<body style="background-color: lightgrey;">
<h1>This is a Heading</h1>
<p>This is a paragraph on a light grey background.</p>
</body>
</html>
Note: Older HTML attributes like bgcolor, color, face, and size (often used with <font> or <body>) are deprecated in HTML5. Use CSS properties instead.

The style attribute accepts one or more CSS property-value pairs.

Syntax:

style="property1: value1; property2: value2; ..."

The property is a CSS property name (e.g., color, font-size, background-color).

The value is the corresponding CSS value for that property (e.g., red, 16px, #ffffff).

Multiple declarations are separated by semicolons (;).

Best Practice: While inline styles work, they mix presentation with structure, making HTML harder to read and maintain. It’s generally better to define styles in <style> blocks within the <head> or, ideally, in separate .css files linked via the <link> element. Inline styles are best reserved for highly specific overrides or styles dynamically applied by JavaScript.

Here are examples of common CSS properties used with the style attribute:

<h1 style="color: blue;">This heading is blue</h1>
<p style="color: green;">This paragraph is green.</p>
<h1 style="font-family: 'Arial', sans-serif;">Arial Heading</h1>
<p style="font-family: 'Courier New', monospace;">Courier New paragraph.</p>
<h1 style="font-size: 3em;">Large Heading (3em)</h1>
<p style="font-size: 14px;">Paragraph with 14px font size.</p>
<p style="font-size: 120%;">Paragraph with 120% font size (relative to parent).</p>
<h1 style="text-align: center;">Centered Heading</h1>
<p style="text-align: right;">Right-aligned paragraph.</p>
<div style="background-color: yellow; padding: 10px;">
This div has a yellow background.
</div>
  • Use the style attribute to apply CSS styles directly to an HTML element (inline styles).
  • The syntax is style="property: value;".
  • Use background-color for background color.
  • Use color for text color.
  • Use font-family for text fonts.
  • Use font-size for text sizes.
  • Use text-align for horizontal text alignment.
  • Prefer external CSS files or <style> blocks over inline styles for better maintainability and separation of concerns.