2.8. Using IDs#
2.8.1. Element IDs#
Every HTML element can have an associated unique identifier. This is useful for when you wish to uniquely style a single element on your page.
Element IDs are assigned using the id attribute, which must be unique
within the HTML document.
Here is an example:
<h1 id="special">My special heading</h1>
<p id="para1">This is a <span id="large-text">paragraph</span> of text.</p>
In the example there are three id’s assigned:
specialto the first level heading<h1>para1to the paragraph<p>large-textto the text in span<span>
Rules for IDs:
ids are case sensitive
ids must contain at least one character
ids cannot start with a number
ids must not contain whitespaces e.g. spaces and tabs
2.8.2. ID Selectors#
To select based on id, use a # followed by the id as the selector e.g.
#id {
property1: value1;
property2: value2
}
An example:
<html>
<head>
<style>
#special {
font-style: italic;
color: orange;
}
#large-text {
font-size: 25px;
}
p {
text-align: center;
}
</style>
<head>
<body>
<h1 id="special">My special heading</h1>
<p id="para1">This is a <span id="large-text">paragraph</span> of text.</p>
<h1>A normal heading</h1>
<p> This is another <span>paragraph</span> of text.</p>
</body>
</html>