W03 Learning Activities: CSS Selectors – Type, Universal, Class, ID
Overview
CSS selectors allow us to target specific elements on the page on which to apply a collection of CSS declarations. It is 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 subject of the
selector.
CSS Selector Types
Selector Type Example CSS Rule Application Universal * { ... }
Applies to all elements Type (Element) h1 { ... }
Applies to all <h1>
elementsClass .red { ... }
Applies to all elements with the "red" class value ID #red { ... }
Applies to the one element with the "red" id value - A class attribute can be applied to many elements on a document. More
than one class can be applied to a single element. The class can be selected by using period (.) notation.
HTML class attribute and CSS class selector examples
HTML CSS <div class="callout highlight active">
<span class="highlight">
.highlight {declarations}
.callout {declarations}
.active {declarations}
- A 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 CSS id
selector using hash (#) notation.
HTML id attribute and CSS id selector example
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
div
elements. - In VS Code, remove the
highlight
class from the second<div>
leaving only one class for that paragraph namedbox
. What happens? You may need to open up the CSS fileCheck Your Understanding
That second div is no longer styled with the "highlight" class and therefore loses those specific declarations.<div class="box">
- In the HTML, attempt to add another
div
element with theid
attribute 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
id
attribute 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