Skip to main content

Understanding HTML Attributes

HTML attributes are additional pieces of information that can be added to HTML elements to modify their behavior or appearance.

Here are some examples of common HTML attributes:

  • id: uniquely identifies an HTML element within a document

  • class: assigns one or more classes to an HTML element for styling purposes

  • src: specifies the source URL for an image, audio or video file, or script file

  • href: specifies the destination URL for a hyperlink

  • alt: provides alternative text for an image, for accessibility purposes

  • style: applies inline styles to an HTML element, such as color, - font, and positioning

  • title: adds a tooltip to an HTML element, displayed when the user hovers over it with the mouse

  • width and height: set the width and height of an image or video element in pixels

  • name: used to give a name to form elements, such as input fields or buttons

As an example:

Here are some examples of HTML attributes in use.

<!-- Assigns the ID "header" to the header element -->
<header id="header">
<h1>Welcome to my website</h1>
<nav>
<!-- Adds the class "nav-link" to each navigation link -->
<a href="#" class="nav-link">Home</a>
<a href="#" class="nav-link">About</a>
<a href="#" class="nav-link">Contact</a>
</nav>
</header>

<!-- Displays an image with a description -->
<img src="example.jpg" alt="Example image" />

<!-- Adds a hyperlink with a tooltip on mouseover -->
<a href="https://www.example.com" title="Visit Example.com"
>Click here to visit Example.com</a
>

<!-- Defines a form input field with a name -->
<label for="name">Name:</label>
<input type="text" id="name" name="user_name" />

In this example:

  • The id attribute is used to uniquely identify an element, while the class attribute can be used to apply a specific style to multiple elements at once.
  • The src and alt attributes are used to specify the source and description of an image, respectively.
  • The title attribute adds a tooltip that appears when the user hovers over an element.
  • The name attribute is used to identify form input fields so that the submitted data can be processed on the server side.