Global Attributes
Overview
Some attributes only work on specific tags (e.g., `src` only makes sense on an `<img>` or `<script>`, `href` only makes sense on an `<a>`).
However, 'Global Attributes' are attributes that you can use on literally ANY HTML element, whether it's a `<p>`, a `<div>`, or a `<button>`. They control universal behaviors like styling, identification, and visibility.
Syntax
The most important global attributes are `class` and `id`. They are used to target elements with CSS and JavaScript.
An `id` must be 100% unique on the page (like a passport number). A `class` can be used on multiple elements (like a uniform worn by many students).
<!-- Applying a reusable class to multiple elements -->
<p class="error-text">Failed to load.</p>
<p class="error-text">Please try again.</p>
<!-- Applying a unique ID to one specific element -->
<nav id="main-navigation">...</nav>`style` allows you to write CSS directly on the element (inline styles). `title` creates a small tooltip when the user hovers their mouse over the element. `hidden` completely removes the element from the screen.
<!-- Adds direct CSS -->
<p style="color: blue; font-size: 20px;">Blue text</p>
<!-- Hover over this to see a tooltip popup -->
<button title="Clicking this will delete your account">Delete</button>
<!-- This paragraph exists in the code, but is invisible on screen -->
<p hidden>Secret loading data...</p>Common Pitfalls
- Never use the exact same 'id' on two different elements. It will break your JavaScript when you try to select it via document.getElementById().
- Avoid using the 'style' attribute heavily. Inline styles are notoriously difficult to manage and override. Always prefer using external CSS files with 'class' attributes.
Real-World Example
Using global attributes to manage a custom tooltip component:
<div
id="tooltip-container"
class="interactive-widget"
title="Detailed information"
style="display: flex; gap: 10px;"
data-custom-info="secret"
tabindex="0"
>
Hover or focus me!
</div>