There are a number of attributes that are valid for every element. The first that we will discuss is technically called the “Global Attribute,” however, we will refer to it as the ‘ID’ attribute.
Following from the idea of identification labels, the ‘ID’ attribute takes as its value a string, which should be a “unique identifier” to that specific element; as in, the ID given to one element should be different from every other element’s ID on a page.
To declare the ‘ID’ attribute of an element, use the standard key="value"
syntax for HTML elements.
<div id="a-unique-id">
You should get in the habit of adding ID attributes to any important HTML elements or elements that you may want to style independently. The ID attribute is one of the ways that we will select elements via CSS to dictate the style and look of our webpages.
In HTML, the following style guide and naming conventions should be used for ID’s:
You should surround your ID value using double quotation marks (as opposed to single).
<!-- Recommended -->
<div id="use-double-quotations">
<!-- Bad Style -->
<div id='do-not-use-single-quotations'>
Use meaningful ID names that reflect the purpose of the element in question.
<!-- Recommended -->
<p id="main-product-p">...</p>
<p id="product-info">...<p>
<!-- Bad Style -->
<p id="importantstuff6">
<p id="p1">
Also, you should use ID names that are as short as possible, but as long as necessary. The goal is to clearly convey what the element is without being unnecessarily verbose.
Technically, in HTML5, ID names must contain at least one character and no spaces. Which leaves all UTF-8 characters as options. (i.e. a-z
, A-Z
, 0-9
, “_
”, “-
”, “:;,?!@#$%^&*+
”, etc.).
However, due to issues that can arise in element selection with CSS and JavaScript, you should follow a more restrictive naming conventions. These conventions are also intended to lend consistency to code between pages and developers, as well as increase readability.
a-z
and 0-9
).-
”) to separate words (as opposed to underscores “_
” or camelCase).<!-- Recommended -->
<div id="an-example-id"></div>
<div id="main-p"></div>
<div id="hero-img"></div>
<div id="row-1"></div>
The above conventions came from:
Read page 183 of Chapter 08 in Duckett.