To add additional information or characteristics to a HTML element we use attributes which is placed inside the opening tag of an element. An attribute consists of a name-value pair.
For example, the lang attribute of the html tag adds information about the language.
In the above example we have added lang attribute to the html opening tag and set its value to en for English.
The most commonly used HTML attributes are the id, class, style and title. These attributes can be used on majority of the HTML elements.
The id attribute is used to uniquely identify an element in a web page. The rule is "NO TWO ELEMENTS MUST HAVE THE SAME id". HTML will not issue any warning if more than one element is having the same id. But it is a bad practice.
Example of id attribute is as followed.
<p id="user-name"> Yusuf Shakeel </p>
<p id="user-country"> India </p>
The class attribute is used to mark more than one element under one group. For example we may have 3 paragraphs all about fruit. So the best way to mark them is to give the class attribute and set the value "fruit".
<p class="fruit"> Apple </p>
<p class="fruit"> Orange </p>
<p class="fruit"> Mango </p>
The style attribute is used to set style of the HTML element. For example if we want to change the text color of the paragraph to white and background color to black then we can use the following style attribute.
<p style="color: white; background-color: black"> Hello World! </p>
We will be learning more about style in CSS tutorials.
The title attribute is used to add title to the HTML element which then is visible as a tooltip when we bring the mouse on top of the element. Following is the example of the title attribute.
<p title="Hello World!"> Place the mouse pointer on top of me! </p>
Place the mouse pointer on top of me!
The href attribute is used in the anchor a tag to redirect to a web link. Following anchor tag will redirect you to the HTML Introduction page of this tutorial on clicking as the href attribute value is set to the HTML Introduction page.
<a href="https://www.dyclassroom.com/html/html-introduction"> HTML Introduction </a>
In case we don't want to set the href attribute of the anchor tag to any web link then we can use the # in the value.
<a href="#"> Anchor tag href attribute set to # </a>
Anchor tag href attribute set to #
The src attribute is used in the img table to display the image on the web page. Following is the img tag whose attribute src is set to the dyclassroom logo image.
The alt attribute is used to display an alternative text is the HTML element fails to get displayed. Following HTML element will display the alt attribute value "Some Image". This is because the image link provided is invalid.
<img src="invalid-image-link-123456.png" alt="Some Image">
Have fun learning :-)
Copyright © 2014 - 2021 DYclassroom. All rights reserved.