CSS Selectors: Type, Universal, Class and ID
Overview
CSS Selectors allow us to target specific elements on the page to apply a CSS rule which rule is a collection of CSS declarations.
"A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them. The element or elements which are selected by the selector are referred to as the subject of the selector." - MDN
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 inside the rule applied to them. The element or
elements which are 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 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. An
element may only have one id per element. 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 your browser, navigate to the "Try-It" section on this MDN page: Class Attribute.
- In the HTML panel, remove the "note" class from the second paragraph
(
<p>
) leaving only one class for that paragraph namededitorial
.
What happens? Use the CSS panel to help you answer the question.Solution Example
That second paragraph is no longer styled with the "note" class and therefore loses the italicized and bold font style and weight. - In the HTML panel, add an
id
attribute to the fourth (last) paragraph (<p>
) and name it "highlight". - In the CSS panel, write a CSS rule for the highlight id selector what
underlines the text and gives a yellowish background to the selected element.
Solution Example
HTML
<p id="highlight" class="note"> ... </p>
CSS
#highlight { text-decoration: underline; background-color: lightyellow; }
Optional Resources
- CSS Selectors - MDN
- Type, Class, and ID Selectors - MDN