Lesson
Selectors in CSS
Completion requirements
Selectors in CSS
Selectors in CSS
CSS selectors let you target HTML elements so you can apply styles to them. Below are the most common selector types with examples and a live rendered demo you can paste into Moodle.
Common selector types
-
Tag selector — targets elements by
tag name (eg.
<p>). -
Class selector — targets elements
with a class using a dot (eg.
.my-class). -
ID selector — targets a unique
element using a hash (eg.
#my-id). -
Attribute selector — targets
elements by attribute (eg.
input[type="text"]). -
Descendant selector — targets
elements that are inside other elements (eg.
.container ul). -
Universal selector —
*targets every element.
Example HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Selectors Demo</title> </head> <body> <div class="container"> <h1 id="heading">Hello World</h1> <ul> <li class="list-item">Item 1</li> <li class="list-item">Item 2</li> <li class="list-item">Item 3</li> </ul> <p data-type="paragraph">This paragraph uses an attribute selector.</p> </div> </body> </html>
Example CSS
/* Tag selector */
ul {
list-style: none;
}
/* Class selector */
.list-item {
color: red;
}
/* ID selector */
#heading {
font-size: 32px;
}
/* Attribute selector */
p[data-type="paragraph"] {
font-style: italic;
}
/* Descendant selector */
.container ul {
margin: 0;
}
/* Universal selector */
* {
box-sizing: border-box;
}
Rendered demo
Hello World
- Item 1
- Item 2
- Item 3
This paragraph is styled as if selected by
p[data-type="paragraph"].
Note: above styles are applied inline in this demo so they render inside Moodle reliably.