On this page
Advanced selectors
Simple selectors
Simple selectors are the foundation of CSS:
- Type:
p,h1,div-- Selects by tag - Class:
.card,.active-- Selects by class - ID:
#header,#main-- Selects by ID (unique) - Universal:
*-- Selects all elements
Combinators
Combinators allow you to select elements based on their relationship with others:
| Combinator | Syntax | Selects |
|---|---|---|
| Descendant | div p |
All p elements inside div |
| Direct child | div > p |
Only p elements that are direct children of div |
| Adjacent sibling | h2 + p |
The p immediately after h2 |
| General sibling | h2 ~ p |
All p siblings after h2 |
Pseudo-classes
Pseudo-classes select elements in a special state:
:hover-- When the mouse is over the element:focus-- When the element has focus:first-child-- First child:nth-child(n)-- Nth child:not(.class)-- Negation
Pseudo-elements
Pseudo-elements allow you to style specific parts of an element:
::before-- Content before the element::after-- Content after the element::first-line-- First line of text::placeholder-- Placeholder text of inputs
In the next lesson, we will learn about the CSS Box Model.
Practice
- Use combinators: Create a
<ul>with nested items and apply different styles using the direct child combinator (>) and the descendant combinator to see the difference. - Style with pseudo-classes: Build a list of 6 elements and use
:nth-child(odd)to color alternate rows. Add a:hovereffect to each item. - Add content with pseudo-elements: Use
::beforeto insert an icon or symbol before each link inside a<nav>.
Did you know?
Attribute selectors like [type="email"] allow you to select elements by their HTML attributes. They are very useful for forms.
/* Descendant combinator */
nav a { color: #333; }
/* Direct child */
ul > li { list-style: disc; }
/* Adjacent sibling */
h2 + p { font-size: 1.1rem; }
/* Pseudo-classes */
a:hover { color: #0066cc; }
input:focus { outline: 2px solid #0066cc; }
li:nth-child(odd) { background: #f5f5f5; }
/* Pseudo-elements */
.quote::before {
content: open-quote;
font-size: 2rem;
}
Sign in to track your progress