W03 Learning Activities: CSS Selectors – Type, Universal, Class, ID
Overview
CSS selectors are the way you specify which elements you want to style. They form the subject line of a CSS rule.
Prepare
A CSS rule's selector is the first part of the rule that tells the browser which HTML elements should have the CSS property values applied. The elements selected by the selector are referred to as the subjects of the selector.
CSS Selector Types
CSS selectors can be different types, depending on whether you want to specify the element by its type, id, or class.
| Selector Type | Example | CSS Rule Application |
|---|---|---|
| Universal | * { ... } |
Applies to all elements |
| Type (Element) | h1 { ... } |
Applies to all <h1> elements |
| Class | .red { ... } |
Applies to all elements with the "red" class value |
| ID | #red { ... } |
Applies to the one element with the "red" id value |
Using the Class Attribute
A class attribute can be applied to many elements in a document. More than one class can be applied to a single element. A class can be selected in CSS by using period (.) notation.
| HTML | CSS |
|---|---|
<div class="callout highlight active"><span class="highlight">
|
.highlight {declarations}.callout {declarations}.active {declarations} |
Using the ID Attribute
An id attribute can only be applied to one element per document, and each element may only have
one id. The id can be selected by a CSS id selector using hash (#) notation.
| HTML | CSS |
|---|---|
<nav id="sub-menu">
|
#sub-menu {declarations} |
Activity Instructions
- In VS Code, open the class-and-id.html file located in the week03 folder.
- Also open the class-and-id.css file located in the week03 styles subfolder.
- Display the page in your browser using Live/Five Server and review the layout and styles applied to the
divelements. - In VS Code, remove the
highlightclass from the second<div>, leaving only one class for that element namedbox. What happens? You may need to open the CSS file to see the difference.Check Your Understanding
<div class="box">That second div is no longer styled with the "highlight" class and therefore loses those specific declarations.
- In the HTML, attempt to add another
divelement with theidattribute of "note" like this:
What happens in VS Code?<div id="note"> <p>Testing the note ID.</p> </div>Check Your Understanding
In VS Code, the editor warns you of a problem by highlighting the duplicate
idattribute with a squiggly line.
Note that the browser will actually apply the CSS style, but this application is an HTML validation error that the browser tries to ignore for you.
Optional Resources
- CSS Selectors – MDN
- Type, Class, and ID Selectors – MDN