π§© Chapter 4: What Are HTML Attributes and Properties?
When writing HTML, tags alone are not enough to control how elements behave or look. We often need to give additional information about an element β and that’s where attributes come in.
β What is an Attribute?
An attribute provides extra information about an HTML tag. It is always specified inside the opening tag, and usually follows this format:
<tagname attribute="value">Content</tagname>
attributeis the name (likehref,src,alt, etc.)valueis the property or setting for that attribute
π Example:
<body bgcolor="red">
In this example:
bgcoloris the attribute"red"is the value (or property) assigned to that attribute
This tells the browser to set the background color of the body to red.
π Common HTML Attributes
| Attribute | Purpose | Example |
|---|---|---|
href |
Sets the URL for a hyperlink | <a href="https://google.com">Link</a> |
src |
Specifies the image path | <img src="logo.png"> |
alt |
Describes the image (used if image canβt load) | <img src="logo.png" alt="My Logo"> |
width, height |
Sets size of image or element | <img src="pic.jpg" width="300"> |
style |
Applies CSS styles directly | <p style="color:blue;">Text</p> |
class |
Assigns a CSS class | <div class="container"> |
id |
Assigns a unique identifier | <h1 id="main-title">Welcome</h1> |
π§ Syntax Rules for Attributes
- Attributes must be inside the opening tag
- Attribute values should be inside quotation marks
- A tag can have multiple attributes, separated by spaces
π Example:
<img src="profile.jpg" alt="Profile Picture" width="200" height="200">
Here:
srcis the attribute,"profile.jpg"is the property (value)alt,width, andheightare other attributes applied to the same tag
π Difference Between Attributes and Properties
Sometimes developers use attribute and property interchangeably, but here’s the key difference:
- Attribute: What you write in HTML (e.g.,
bgcolor="red") - Property: The actual value or setting of that attribute (e.g.,
red)
Think of it like this:
π§± Attribute = Key
π¨ Property = Value
π Summary
| Term | Definition | Example |
| Attribute | Extra info added to an HTML element | bgcolor, href, src |
| Property | The specific value assigned to that attribute | "red", "https://..." |
