HTML Docs

HTML Attributes

A guide to understanding HTML attributes, including global, data, and boolean attributes.

HTML attributes provide additional information about HTML elements and help define their behavior and presentation on a webpage.

🔗 Global Attributes

Global attributes can be applied to any HTML element. These attributes are used to control the general behavior or appearance of the element. Some commonly used global attributes are:

  • id: A unique identifier for an element.
  • class: Specifies one or more class names for an element.
  • style: Allows you to apply inline CSS styles to an element.
  • title: Specifies extra information about an element (usually displayed as a tooltip).
  • lang: Specifies the language of the element's content.

Example:

<div id="header" class="main-header" style="background-color: lightblue;" title="Main Header" lang="en">
  Welcome to the website!
</div>

In this example:

  • The id attribute assigns a unique identifier.
  • The class attribute specifies a class for styling.
  • The style attribute applies inline CSS.
  • The title attribute adds a tooltip.
  • The lang attribute specifies the language.

📊 Data Attributes

Data attributes are used to store custom data private to the page or application. They start with data- and can be accessed using JavaScript.

Example:

<button data-user-id="1234" data-action="save">Save</button>

In this example:

  • data-user-id="1234" stores the user's ID.
  • data-action="save" describes the button's action.

✅ Boolean Attributes

Boolean attributes represent true/false values. If the attribute is present, its value is true, even if no value is specified.

Example:

<input type="checkbox" checked>
<input type="text" readonly>
<button disabled>Disabled Button</button>

In this example:

  • checked makes the checkbox selected.
  • readonly makes the text input non-editable.
  • disabled disables the button.

⚡ Key Differences in HTML Attributes

Attribute TypeExampleDescription
Global Attributesid, class, style, title, langCommon attributes used across many HTML elements
Data Attributesdata-action="submit", data-user-id="1234"Store custom data that can be accessed via JavaScript
Boolean Attributeschecked, disabled, readonlySpecify boolean states for elements

Pro Tip: When using data attributes, use camelCase for multi-word names like data-userId to keep naming consistent in JavaScript.

🧪 Try Yourself

import "./styles.css";

document.getElementById("app").innerHTML = `
<h1>Hello world</h1>
`;

📝 Conclusion

HTML attributes are essential for enhancing the functionality, behavior, and presentation of elements.

  • Global attributes apply to all elements.
  • Data attributes store extra information.
  • Boolean attributes toggle simple true/false states.

Warning: Always make sure id attributes are unique on the page to avoid conflicts.

📚 Resources

On this page