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 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 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
- Navigate to this CodePen: Class and ID Attributes
- 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 answer the question.Check Your Understanding
That second paragraph is no longer styled with the "note" class and therefore loses the italicized font style, bold font weight, and color.<p class="editorial">
- In the HTML panel, add an
id
attribute to the fourth (last) paragraph<p>
and name ithighlight
. - In the CSS panel, write a CSS rule for the
highlight
id selector with CSS declarations that- underlines the text
- applies a yellowish background color
- adds some whitespace around the text (padding)
Check Your Understanding
HTML Alterations
<p id="highlight" class="note"> ... </p>
CSS Alterations
#highlight { text-decoration: underline; background-color: lightyellow; padding: 1rem; }
Optional Resources
- CSS Selectors - MDN
- Type, Class, and ID Selectors - MDN