You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Selectors are the heart of CSS — they determine which elements your styles apply to. Mastering selectors gives you precise control over the appearance of your web pages. Combined with the cascade, specificity, and inheritance, selectors form the foundation of how CSS works.
Targets all instances of an HTML element:
p {
color: #333;
line-height: 1.6;
}
Targets elements with a specific class attribute. Prefixed with a dot (.):
.card {
background: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
<div class="card">This is a card.</div>
<div class="card">Another card.</div>
Targets a single element with a specific id. Prefixed with a hash (#):
#header {
background-color: navy;
color: white;
padding: 20px;
}
<header id="header">Site Header</header>
Best practice: Prefer classes over IDs for styling. IDs have very high specificity and should be unique per page. Classes are reusable and easier to maintain.
Targets every element on the page:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
| Combinator | Syntax | Description | Example |
|---|---|---|---|
| Descendant | A B | B is any descendant of A | nav a — all links inside a <nav> |
| Child | A > B | B is a direct child of A | ul > li — direct children only |
| Adjacent sibling | A + B | B is immediately after A | h2 + p — first <p> after an <h2> |
| General sibling | A ~ B | B is any sibling after A | h2 ~ p — all <p> siblings after an <h2> |
/* Only links inside the nav */
nav a {
color: white;
text-decoration: none;
}
/* Only direct children of .menu */
.menu > li {
display: inline-block;
}
/* Style the first paragraph after every h2 */
h2 + p {
font-size: 1.1rem;
color: #555;
}
Target elements based on their attributes:
| Selector | Description | Example |
|---|---|---|
[attr] | Has the attribute | [required] |
[attr="val"] | Exact match | [type="email"] |
[attr^="val"] | Starts with | [href^="https"] |
[attr$="val"] | Ends with | [href$=".pdf"] |
[attr*="val"] | Contains | [class*="btn"] |
/* Style all required inputs */
input[required] {
border: 2px solid red;
}
/* Style external links */
a[href^="https"] {
color: blue;
}
/* Style PDF links */
a[href$=".pdf"]::after {
content: " (PDF)";
}
Pseudo-classes target elements in a specific state:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.