<New code>
HTML
id="exampleId"
- assigns an Id to an HTML element
CSS
#exampleId {}
- assigns styles to a particular Id
Sometimes you want to style elements individually
Right now, you know how to apply CSS styles by applying them to tags, like this:
<style>
p {
color: Red;
font-size: 24px;
font-weight: bold;
}
</style>
This works well if you want all of the paragraphs, or images, or tables, or list items to have the same style.
But what if you want one of the list items to have a different style?
Assigning an id
to an element
In that case, you give that element an identity. For example, let's say you want to make one list item red:
<body>
<h2>Top Selling Mobile Phones of All Time</h2>
<ol>
<li>Nokia 1100</li>
<li>Nokia 1110</li>
<li id="redThingId">Nokia 1200</li>
<li>Nokia 5230</li>
<li>Nokia 3210</li>
</ol>
</body>
Assigning a style to an
id
with #
Now if you add the following code to the
<head>
of your document:
<style>
#redThingId {
color: Red;
}
</style>
Note that the Id, redThingId
has a hash tag in front of it.
This is used in CSS to apply a style to a single Id
instead of every tag with that name.
The list will now display as:
Top Selling Mobile Phones of All Time
- Nokia 1100
- Nokia 1110
- Nokia 1200
- Nokia 5230
- Nokia 3210
Potential troubles using Ids
-
BIGGEST STYLE CHALLENGE:
use
id
in the HTML tag andId
inside the quotes and CSS — For example:<p id="exampleId">
-
Spelling and capitalization count —
myAwesomeId
andMyAwesomeId
are not the same. - Use camelCase to name Ids — As you will see, variables, functions, and Ids should use camelCase. This means that the first word is lowercase, and any additional words have the first letter capitalized.
-
You can't use spaces —
So
id="my AwesomeId"
will not work. - You can only have one element with a single Id in each HTML page — On some browsers this will break your page, on others, it will work. You probably don't want this kind of unpredictability.
- What if you want the same style affect more than one element — Funny you should ask. That is what CSS classes are for...
Learn more
- Khan Academy on selecting by Id
- w3schools.com on CSS selectors