WDD 130: Web Fundamentals

W03 Learning Activities: CSS Selectors – Type, Universal, Class, ID

Overview

CSS selectors are the way you specify the element you want to style. 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

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 on a document. More than one class can be applied to a single element. The class can be selected by using period (.) notation.

HTML CSS
<div class="callout highlight active">
<span class="highlight">
.highlight {declarations}
.callout {declarations}
.active {declarations}

Using the ID

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 CSS id selector using hash (#) notation.

HTML CSS
<nav id="sub-menu"> #sub-menu {declarations}

Activity Instructions

  1. In VS Code, open the class-and-id.html file located in the week03 folder.
  2. Also open the class-and-id.css file located in the week03 styles subfolder.
  3. Display the page in your browser using Live/Five Server and review the layout and styles applied to the div elements.
  4. In VS Code, remove the highlight class from the second <div> leaving only one class for that paragraph named box. What happens? You may need to open up the CSS file
    Check Your Understanding

    <div class="box">
    That second div is no longer styled with the "highlight" class and therefore loses those specific declarations.

  5. In the HTML, attempt to add another div element with the id attribute of "note" like this
    <div id="note">
      <p>Testing the note ID.</p>
    </div>
    What happens in VS Code?
    Check Your Understanding

    In VS Code, the editor warns you of a problem by highlighting the duplicate id attribute with a squiggly line.

    Duplicate ID Warning

    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