Skip to main content

Html Attributes

HTML attributes are special words used to control the behavior of an HTML element. They provide additional information about an HTML element and are always specified in the start tag.

The Syntax of an HTML Attribute

HTML attributes are always included in the opening tag and come in name/value pairs like: name="value"

Here's an example of what an HTML attribute looks like:

<a href="https://www.google.com">This is a link</a>

In the example above, href is an attribute name and https://www.google.com is its value. The entire href="https://www.google.com" segment is the HTML attribute. This particular attribute tells your browser where to go when the link is clicked.

Common HTML Attributes

There are many HTML attributes but some of the most common ones include:

  1. Class Attribute: Used to specify one or more classnames for an element. The class attribute is mostly used to point to a class in a style sheet.
<div class="city">London</div>
  1. Id Attribute: The id attribute specifies a unique id for an HTML element. The value of the id attribute must be unique within the HTML document.
<h1 id="title">HTML Attributes</h1>
  1. Style Attribute: Used to add styles to an element, such as color, font, size, and more. The style attribute will apply the specified styles directly to that element.
<p style="color:red;">This is a red paragraph.</p>
  1. Src Attribute: Src stands for "source". The src attribute is used to specify the path to the image you want to display.
<img src="smiley.gif" alt="Smiley face">
  1. Alt Attribute: The alt attribute specifies an alternative text to be used, if an image cannot be displayed.
<img src="smiley.gif" alt="Smiley face">
  1. Width and Height Attributes: The width and height attributes are used to specify the width and height of an image.
<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">

Boolean Attributes

Boolean attributes are a special type of attribute that can either be true or false. They only have a single value, which is their name. If a boolean attribute is present, its value is considered to be true. If it is absent, its value is considered to be false.

For example, the disabled attribute is a boolean attribute. If it is present in the <input> tag, the input field is disabled.

<input type="text" disabled>

In the example above, the disabled attribute is present, so the input field is disabled.

Conclusion

HTML attributes are a powerful way to control how HTML elements behave and appear on your page. They give you a lot of control over your HTML, allowing you to create more complex and interactive web pages. It's important to familiarize yourself with the different HTML attributes and how to use them as they are a core part of learning HTML.