What is Style Attribute in HTML: Simple Explanation and Examples
style attribute in HTML lets you add CSS styles directly to an HTML element. It changes how that element looks by setting properties like color, size, or spacing right inside the tag.How It Works
The style attribute works like a quick way to decorate a single HTML element. Imagine you have a plain white wall and you want to paint just one spot a different color. Instead of painting the whole room, you just paint that spot. Similarly, the style attribute lets you add CSS rules directly inside an element's tag to change its appearance.
It uses CSS syntax inside quotes, like color: red; or font-size: 20px;. The browser reads these instructions and applies them only to that element, ignoring other elements unless they have their own styles.
Example
This example shows how to use the style attribute to make a paragraph text red and bigger.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Style Attribute Example</title> </head> <body> <p style="color: red; font-size: 1.5rem;">This text is red and larger because of the style attribute.</p> <p>This text is normal without style.</p> </body> </html>
When to Use
Use the style attribute when you want to quickly change the look of a single element without writing separate CSS rules. It's handy for small tweaks or testing styles fast.
For example, if you want to highlight one word in a sentence or change the color of a button temporarily, the style attribute is perfect. However, for bigger projects or repeated styles, using separate CSS files or <style> blocks is better for keeping code clean and easy to maintain.
Key Points
- The
styleattribute adds CSS directly to an HTML element. - It affects only the element it is on, not others.
- Use it for quick, small style changes.
- For many elements or complex styles, external CSS is better.
- Always write valid CSS syntax inside the attribute.