id
Objectives:
Set up html and css files with css file link in head.
Test set up with a color change: body { background-color: blue; }
Reveal info about ids.
Show difference between ids and classes.
File Location
You should be located in the following files:
javascript-library
└── 0-PreWork
...
└── 2-CSS-Basics
└──02-ids.css
└──02-ids.htmlDescription
The id attribute is a unique identifier. Where a class attribute can be applied to many different elements, an id points to only one element. This allows you to manipulate that particular element without worrying about affecting anything else.
Furthermore, an id takes precedent over classes. If, for example, you have conflicting CSS styling on a particular element, one under a class element and the other under an id, the id attribute will be used. This allows you to prioritize your styling and, if needed, overrule generalized styling of your app.
Sample Code
Sample Code
CSS:
Discussion
Having the knowledge of classes under our belts, we can examine the uses of id. When we want to target several elements, class is the right choice. If we're trying to target a single element, that's when id is preferable. In our above example, we've shown not only how to target with an id, but also proven that multiple classes can be assigned to a single element. Finally, it's important to recognize that our very last <p> has both an id and a class!
Take note of the detail that when a property is assigned a conflicting value in both an id and a class, such as our #number-one and .first-class, the id has preference. In the case of our example, this means that color receives the value of "red".
Challenge
Experiment with id, and try testing new properties.
Last updated