Identifying with ids
There are a number of attributes that you can apply to every element. The first that we will discuss is technically called the “global identifier,” but we will refer to it as the id attribute. We learned a little bit about this attribute already last week.
To declare the id attribute of an element, use the standard name="value"
format for writing attributes. Remember, all attributes have a name (also called a key), followed by an equals sign, and then the value is wrapped in quotation marks afterward. With the id attribute, you get to decide on the value.
Important The id given to one element should be different from every other elements’ id on the page!
<div id="a-unique-id"></div>
<div id="another-unique-id"></div>
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 (and eventually JavaScript in MART 441) to dictate the style and look of our webpages.
Naming Practices for ids
In HTML, the following style guide and naming conventions should be used for ids:
- HTML Value Quotation Marks - You should surround your id value using quotation marks (as opposed to single apostrophes).
- ID Naming - Use meaningful id names that reflect the purpose of the element in question, like “contact” rather than “paragraph4”.
- Acceptable Characters - 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.
- Use lowercase letters or number (i.e.
a-z
and0-9
). - Start an id name with a lowercase letter.
- Use hyphens (“
-
”) to separate words (as opposed to underscores “_
” or camelCase).
<!-- Recommended: -->
<div id="use-double-quotations">
<div id="contact">
<div id="image-gallery-1">
<!-- Bad Style: -->
<div id='do-not-use-single-quotations'>
<div id='paragraph4'>
<div id='Image_Gallery-1!'>
Note 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.
- Previous
- Next