HTML Attributes
Attributes
provide additional information about an element's behavior, style, or data and are used to control the element's behavior in HTML.
HTML attributes are included in the start tag and written in the format
name="value"
.
<elementName attributeName="attributeValue"> ... </elementName>
How can you use attributes?
The src
attribute is a required attribute for the <img>
tag, specifying the path of the image to be displayed.
<img src="imagePath.jpg" alt="Image description" />
An img tag without a defined src attribute will not display an image.
Examples of Key Attributes
Let's look into some key attributes used in HTML elements.
First, we'll examine attributes that can be used with all HTML elements.
Common Attributes for All HTML Tags: class
and id
Use the id
attribute to assign a unique identifier to a specific element, and the class
attribute to apply the same style to multiple elements.
class
Used to apply the same style to multiple elements. Different elements can share the same class name.
<div class="highlight">Applies highlight class</div>
id
Used to distinguish a specific element or select an element via JavaScript. The id
value must be unique within the HTML document.
<div id="main-content">HTML element with main-content ID</div>
Attributes Specific to Certain Tags
Some attributes are only applicable to specific tags. Let's examine two examples below.
Unique Attributes for the img Tag: src
, alt
In the img
element, src
specifies the path of the image, while alt
provides alternative text if the image cannot be displayed.
<img src="https://picsum.photos/id/237/300" alt="Dog" />
Unique Attribute for the a Tag: href
In the a
element, which creates a hyperlink for navigating to another page, the href
attribute specifies the URL of the page to navigate to.
The target
attribute determines whether the page opens in a new window when the link is clicked. target="_blank"
opens the page in a new window.
<a href="https://codefriends.net" target="_blank">Link</a>
Follow the highlighted sections in the code to try it yourself.
Where are attributes located in an HTML element tag?
Both the opening and closing tags
Opening tag
Closing tag
Content
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help