CSS Selectors
Learn how CSS selectors target HTML elements using element, class, ID, universal, grouping, descendant, child, sibling, attribute, pseudo-class, and pseudo-element selectors.
Introduction
In the previous lesson, you learned the syntax used to write CSS rules.
You learned that every standard CSS rule begins with a selector.
Now it is time to understand selectors in detail.
Selectors are one of the most important parts of CSS because they decide exactly which HTML elements should receive a style.
Without selectors, the browser would know what style to apply but would not know which elements should receive it.
The selector answers one important question: Which HTML element or elements should receive these styles?
What are CSS Selectors?
A CSS selector is a pattern used to find and target HTML elements.
After the browser finds elements that match the selector, it applies the declarations written inside the rule.
p {
color: blue;
}In this example, p is the selector.
The browser searches the document for every <p> element and applies the blue text color.
<h1>CSS Selectors</h1>
<p>First paragraph</p>
<p>Second paragraph</p>| Selector | Target |
|---|---|
| p | All paragraph elements |
| h1 | All level-one headings |
| .card | Elements with class="card" |
| #header | Element with id="header" |
| * | All elements |
Why Do We Need Selectors?
A webpage can contain hundreds or thousands of HTML elements.
Different elements need different styles.
Selectors allow developers to control exactly where CSS rules should apply.
<h1>Main Heading</h1>
<p>Normal paragraph</p>
<p class="important">
Important paragraph
</p>
<button>Submit</button>h1 {
color: purple;
}
p {
color: gray;
}
.important {
color: red;
}
button {
background-color: green;
color: white;
}Without Precise Selectors
- Every element may receive the same style.
- Specific elements are difficult to target.
- Reusable designs become difficult.
- Large pages become hard to control.
- Styles may affect unwanted elements.
With Precise Selectors
- Target exact elements.
- Create reusable classes.
- Style unique sections.
- Control nested elements.
- Build maintainable interfaces.
The better you understand selectors, the more accurately you can control the appearance of a webpage.
Real-World Analogy
Imagine a teacher giving instructions to students in a classroom.
The teacher can give an instruction to everyone, a group of students, one specific student, or students with a particular characteristic.
| Classroom Instruction | CSS Selector |
|---|---|
| All students | Universal selector |
| All students in Grade 10 | Element or class selector |
| Students in the red team | Class selector |
| Student with roll number 25 | ID selector |
| Students carrying laptops | Attribute selector |
Everyone → Stand up
Red Team → Move left
Student #25 → Answer the question
Students with laptops → Open the browser* {
box-sizing: border-box;
}
.red-team {
color: red;
}
#student-25 {
font-weight: bold;
}
[data-device="laptop"] {
background-color: yellow;
}CSS provides different selector types so you can target elements based on their tag, class, ID, position, relationship, attribute, or state.
Basic Selector Syntax
A selector is written before the declaration block.
selector {
property: value;
}h1 {
color: blue;
}h1 {
│
│ color: blue;
│
}
│
└── SelectorThe selector can be simple or complex.
p { }
.card { }
#header { }nav a { }
.card > h2 { }
input[type="email"] { }
button:hover { }| Selector | Meaning |
|---|---|
| p | Every <p> element |
| .card | Every element with class="card" |
| #header | The element with id="header" |
| nav a | Links inside <nav> |
| button:hover | A button while the pointer is over it |
Types of CSS Selectors
CSS provides many selector types for different targeting requirements.
| Selector Type | Syntax | Purpose |
|---|---|---|
| Element | p | Targets HTML elements by tag name |
| Class | .card | Targets elements by class |
| ID | #header | Targets an element by ID |
| Universal | * | Targets all elements |
| Grouping | h1, h2 | Targets multiple selectors |
| Descendant | div p | Targets nested descendants |
| Child | div > p | Targets direct children |
| Adjacent Sibling | h2 + p | Targets the next sibling |
| General Sibling | h2 ~ p | Targets following siblings |
| Attribute | [type="text"] | Targets by attribute |
| Pseudo-Class | :hover | Targets a state or condition |
| Pseudo-Element | ::first-letter | Targets part of an element |
1. Element Selector
The element selector targets HTML elements using their tag name.
element {
property: value;
}p {
color: blue;
}This rule selects every <p> element on the page.
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>h1 {
color: purple;
}
button {
background-color: green;
}
a {
color: red;
}| Selector | Targets |
|---|---|
| h1 | All <h1> elements |
| p | All <p> elements |
| button | All <button> elements |
| img | All <img> elements |
| a | All <a> elements |
If a page contains 100 paragraph elements, the p selector can match all 100 of them.
2. Class Selector
The class selector targets elements that contain a specific class attribute value.
A class selector begins with a dot followed by the class name.
.class-name {
property: value;
}<p class="highlight">
Important paragraph
</p>
<p>
Normal paragraph
</p>
<div class="highlight">
Important box
</div>.highlight {
background-color: yellow;
}The class can be reused on different elements.
<h2 class="success">Payment Successful</h2>
<p class="success">Your order is confirmed.</p>
<button class="success">Continue</button>.success {
color: green;
}The same class can be added to many elements, making class selectors ideal for reusable styles.
3. ID Selector
The ID selector targets an element using its id attribute.
An ID selector begins with a hash symbol followed by the ID value.
#id-name {
property: value;
}<header id="main-header">
Welcome to PrograMinds
</header>#main-header {
background-color: purple;
color: white;
padding: 20px;
}Class Selector
- Starts with a dot.
- Designed for reusable grouping.
- Can be shared by many elements.
- Example: .card
ID Selector
- Starts with a hash symbol.
- Identifies a specific element.
- An ID should be unique in a document.
- Example: #main-header
An id value should identify one unique element in the HTML document.
4. Universal Selector
The universal selector uses an asterisk and can match all elements.
* {
property: value;
}* {
box-sizing: border-box;
}This rule applies box-sizing: border-box to every element.
<h1>Heading</h1>
<p>Paragraph</p>
<button>Button</button>* {
color: blue;
}The universal selector can affect a large number of elements, so understand the effect of the declarations you place inside it.
5. Grouping Selector
The grouping selector allows multiple selectors to share the same declarations.
Selectors are separated with commas.
h1 {
color: purple;
}
h2 {
color: purple;
}
h3 {
color: purple;
}h1,
h2,
h3 {
color: purple;
}<h1>Main Heading</h1>
<h2>Section Heading</h2>
<h3>Subheading</h3>
<p>Normal paragraph</p>When different selectors need exactly the same declarations, grouping can keep the stylesheet shorter and easier to maintain.
Selector Combinators
Combinators describe relationships between selectors.
They allow CSS to target elements based on where they appear relative to other elements.
| Combinator | Syntax | Relationship |
|---|---|---|
| Descendant | A B | B anywhere inside A |
| Child | A > B | B directly inside A |
| Adjacent Sibling | A + B | B immediately after A |
| General Sibling | A ~ B | B siblings after A |
<div>
<h2>Heading</h2>
<p>First paragraph</p>
<section>
<p>Nested paragraph</p>
</section>
<p>Last paragraph</p>
</div>Combinators allow you to target elements according to their position and relationship in the HTML structure.
6. Descendant Selector
The descendant selector targets elements located anywhere inside another element.
A space is written between the selectors.
parent descendant {
property: value;
}<article>
<p>Direct paragraph</p>
<div>
<p>Nested paragraph</p>
</div>
</article>
<p>Outside paragraph</p>article p {
color: blue;
}Both paragraphs inside the article match, even though one is nested inside another div.
The descendant does not need to be a direct child. It can appear at any depth inside the ancestor.
7. Child Selector
The child selector targets only elements that are direct children of another element.
The greater-than symbol is written between the selectors.
parent > child {
property: value;
}<article>
<p>Direct child paragraph</p>
<div>
<p>Nested paragraph</p>
</div>
</article>article > p {
color: red;
}Descendant: article p
- Matches direct children.
- Matches deeply nested elements.
- Searches at any depth.
Child: article > p
- Matches direct children only.
- Does not match deeper descendants.
- More structurally specific.
8. Adjacent Sibling Selector
The adjacent sibling selector targets an element that appears immediately after another element at the same parent level.
A plus symbol is written between the selectors.
first + next {
property: value;
}<h2>Section Heading</h2>
<p>First paragraph</p>
<p>Second paragraph</p>h2 + p {
color: red;
}Only the first paragraph matches because it appears immediately after the <h2>.
The adjacent sibling selector does not target every following sibling. It targets only the first matching element immediately after the first selector.
9. General Sibling Selector
The general sibling selector targets matching siblings that appear after another element.
A tilde symbol is written between the selectors.
first ~ sibling {
property: value;
}<h2>Section Heading</h2>
<p>First paragraph</p>
<div>Information Box</div>
<p>Second paragraph</p>
<p>Third paragraph</p>h2 ~ p {
color: purple;
}Adjacent Sibling: +
- Targets the immediate next sibling.
- Only one position is considered.
- Example: h2 + p
General Sibling: ~
- Targets matching later siblings.
- Can match multiple elements.
- Example: h2 ~ p
10. Attribute Selector
Attribute selectors target elements according to the presence or value of an HTML attribute.
[attribute] {
property: value;
}<input type="text">
<input type="email">
<input type="password">input[type="email"] {
border: 2px solid blue;
}| Selector | Meaning |
|---|---|
| [disabled] | Elements containing disabled |
| [type="email"] | Elements where type is exactly email |
| [class~="card"] | Elements whose class list contains card |
| [href^="https"] | href begins with https |
| [href$=".pdf"] | href ends with .pdf |
| [href*="example"] | href contains example |
input[disabled] {
background-color: lightgray;
}
a[href^="https"] {
color: green;
}
a[href$=".pdf"] {
font-weight: bold;
}Attribute selectors are especially useful for form controls, links, states, and custom data attributes.
11. Pseudo-Class Selector
A pseudo-class selects an element based on a state, condition, or structural position.
Pseudo-classes begin with a single colon.
selector:pseudo-class {
property: value;
}<button>
Move Mouse Over Me
</button>button {
background-color: blue;
color: white;
}
button:hover {
background-color: green;
}| Pseudo-Class | Purpose |
|---|---|
| :hover | Pointer is over the element |
| :focus | Element has keyboard or input focus |
| :active | Element is being activated |
| :checked | Checkbox or radio is checked |
| :disabled | Form control is disabled |
| :first-child | Element is the first child |
| :last-child | Element is the last child |
| :nth-child() | Element matches a structural position |
li:first-child {
color: red;
}
li:last-child {
color: green;
}They allow CSS to respond to interaction, form states, and an element position in the document structure.
12. Pseudo-Element Selector
A pseudo-element targets a specific part of an element or creates a styleable generated box.
Modern pseudo-element syntax normally uses two colons.
selector::pseudo-element {
property: value;
}<p>
Cascading Style Sheets control the appearance of webpages.
</p>p::first-letter {
color: red;
font-size: 40px;
}| Pseudo-Element | Targets |
|---|---|
| ::first-letter | First letter of text |
| ::first-line | First rendered line of text |
| ::before | Generated box before content |
| ::after | Generated box after content |
| ::selection | User-selected text |
| ::placeholder | Placeholder text in form controls |
.price::before {
content: "₹";
}
.required::after {
content: " *";
color: red;
}Pseudo-Class
- Uses a single colon.
- Targets a state or condition.
- Example: :hover
- Example: :first-child
Pseudo-Element
- Normally uses two colons.
- Targets a part or generated box.
- Example: ::first-letter
- Example: ::before
Combining Selectors
Selectors can be combined to create more precise targeting patterns.
<article class="card">
<h2>CSS Course</h2>
<p class="description">
Learn CSS step by step.
</p>
<a href="/css">
Start Learning
</a>
</article>.card h2 {
color: purple;
}
.card .description {
color: gray;
}
.card > a {
color: green;
}
.card a:hover {
color: red;
}| Selector | Meaning |
|---|---|
| .card h2 | h2 elements anywhere inside .card |
| .card .description | .description elements inside .card |
| .card > a | Direct a children of .card |
| .card a:hover | Links inside .card while hovered |
| button.primary | button elements with class primary |
A selector can be technically valid but still be difficult to understand. Use the simplest selector that reliably targets the intended elements.
Selector Specificity
Sometimes multiple CSS selectors match the same element and try to set the same property.
Specificity is one of the rules the browser uses to determine which declaration wins.
<p
id="message"
class="important"
>
Welcome to CSS
</p>p {
color: blue;
}
.important {
color: green;
}
#message {
color: red;
}The ID selector has greater specificity than the class selector and element selector, so the text becomes red.
| Selector Category | Example | General Strength |
|---|---|---|
| Element | p | Lower |
| Class / Attribute / Pseudo-Class | .card | Higher |
| ID | #header | Higher still |
| Inline Style | style="..." | Very strong in normal author styling |
Specificity is important, but it is not the only rule that decides the final style. Importance, origin, cascade layers, and source order can also affect the result.
How Browser Matches Selectors
The browser parses CSS selectors and determines which elements in the document match each selector.
<div class="card">
<h2>CSS Course</h2>
<p>Learn selectors.</p>
</div>
<div>
<h2>HTML Course</h2>
</div>.card h2 {
color: purple;
}| Element | Matches .card h2? | Reason |
|---|---|---|
| CSS Course h2 | Yes | It is an h2 inside .card |
| Paragraph | No | It is not an h2 |
| HTML Course h2 | No | It is not inside .card |
A perfectly valid CSS declaration has no effect when the selector does not match the intended element.
Browser Rendering Flow
Selector matching is an important part of the browser rendering process.
CSS Selector
│
▼
Parse Selector
│
▼
Search for Matches
│
▼
Check Element Structure
│
▼
Check Classes / IDs / Attributes
│
▼
Check States and Conditions
│
▼
Collect Matching Rules
│
▼
Resolve Cascade
│
▼
Calculate Final Styles
│
▼
Render Page| Stage | Purpose |
|---|---|
| Parse Selector | Understand the selector pattern |
| Match Elements | Find elements that satisfy the pattern |
| Collect Rules | Gather declarations from matching rules |
| Resolve Cascade | Determine winning declarations |
| Calculate Styles | Create final computed values |
| Render | Display the styled result |
Real-World Applications
CSS selectors are used throughout modern websites and applications.
Navigation Menus
Target links, active items, nested menus, and hover states.
Cards
Style card titles, descriptions, images, buttons, and variants.
Forms
Target input types, required fields, checked controls, and focus states.
Tables
Style rows, columns, headers, and alternating positions.
E-Commerce
Target product cards, sale badges, prices, and action buttons.
Responsive Components
Apply styles to reusable classes across different layouts.
Learning Platforms
Style lessons, code blocks, sidebars, navigation, and progress states.
Dashboards
Target complex nested components and interface states.
Advantages
CSS selectors provide flexible and precise control over webpage styling.
Precise Targeting
Style exactly the elements you need.
Reusability
Classes allow styles to be shared across many elements.
Structural Control
Combinators target elements according to relationships.
Interactive States
Pseudo-classes respond to hover, focus, checked, and other conditions.
Attribute Targeting
Style elements based on HTML attributes and values.
Partial Styling
Pseudo-elements style specific parts or generated boxes.
Maintainability
Well-designed selectors make stylesheets easier to manage.
Scalability
Reusable selector strategies support large interfaces.
Common Beginner Mistakes
Write .card in CSS to target class="card".
Write #header in CSS to target id="header".
Write p for a paragraph element, not .p unless the HTML actually uses class="p".
#card targets an ID, while .card targets a class.
An ID value should identify one unique element in the document.
Heavy ID usage can create unnecessarily strong and difficult-to-override selectors.
A space matches descendants at any depth, while > matches direct children only.
+ targets the immediate next sibling, while ~ targets matching later siblings.
h1, h2 targets both elements, while h1 h2 means h2 elements inside h1 elements.
.card .title and .card.title have different meanings.
Attribute selectors require square brackets.
Quoted attribute values are often clearer and safer when values contain special characters.
:hover represents a state, while ::before represents a pseudo-element.
Touch devices may not provide the same hover interaction as pointer devices.
Deep selector chains are difficult to understand and maintain.
Excessive specificity makes later overrides more difficult.
Later declarations do not always win when specificity or other cascade rules differ.
Importance, origin, layers, specificity, and source order can all affect the winner.
Valid declarations cannot style an element when the selector does not match it.
Developer tools can show matched, unmatched, and overridden CSS rules.
Best Practices
- Use the simplest selector that reliably targets the intended element.
- Use element selectors for broad default styles.
- Use classes for reusable component styles.
- Keep class names meaningful.
- Choose class names based on purpose rather than temporary appearance when possible.
- Use IDs primarily when a unique document identifier is genuinely useful.
- Avoid using IDs for every reusable visual style.
- Keep ID values unique within the document.
- Remember that element selectors do not use a prefix.
- Remember that class selectors begin with a dot.
- Remember that ID selectors begin with a hash symbol.
- Remember that the universal selector uses an asterisk.
- Use commas to group independent selectors.
- Do not confuse selector grouping with descendant selection.
- Write h1, h2 to target both headings.
- Write h1 h2 only when targeting h2 elements inside h1 elements.
- Use descendant selectors when any nesting depth is acceptable.
- Use child selectors when the direct parent-child relationship matters.
- Use adjacent sibling selectors for the immediate next sibling.
- Use general sibling selectors for matching later siblings.
- Use attribute selectors when the attribute itself represents the styling condition.
- Use exact attribute matching when exact values matter.
- Use prefix, suffix, and substring attribute selectors carefully.
- Use pseudo-classes for states and structural conditions.
- Provide visible focus styles for keyboard users.
- Do not remove focus indicators without providing an accessible replacement.
- Do not depend only on hover for essential information.
- Use :checked for appropriate form-control states.
- Use :disabled for disabled form controls.
- Use structural pseudo-classes when they accurately represent the document structure.
- Use pseudo-elements for decorative or partial styling.
- Use ::before and ::after carefully.
- Remember that ::before and ::after commonly require the content property to generate content.
- Do not place essential information only in generated decorative content.
- Keep selector chains short when possible.
- Avoid deeply nested selectors.
- Avoid unnecessary specificity.
- Prefer reusable classes over highly specific structural selectors for components.
- Do not add selectors only to increase specificity without understanding the conflict.
- Understand why a rule loses before increasing selector strength.
- Use browser developer tools to inspect matched rules.
- Check whether a selector is actually matching the intended element.
- Check whether another rule overrides the declaration.
- Check inherited values when debugging text styles.
- Check specificity when multiple rules set the same property.
- Check source order when competing declarations otherwise have equal priority.
- Remember that specificity is only one part of the cascade.
- Learn the difference between selector matching and cascade resolution.
- A selector first determines whether a rule applies.
- The cascade then determines which competing declaration wins.
- Keep naming conventions consistent.
- Use a project-wide class naming strategy when working on large applications.
- Avoid class names that are difficult to understand.
- Avoid random abbreviations unless the team understands them.
- Avoid styling elements through unstable generated class names.
- Avoid depending excessively on exact DOM depth.
- Use component-level classes for reusable UI.
- Use state classes when an application explicitly manages state.
- Use data attributes when they represent meaningful data or state.
- Do not use attribute selectors as a replacement for every class.
- Balance precision with readability.
- Test selectors after HTML structure changes.
- Review selectors during component refactoring.
- Remove unused selectors when safe.
- Do not leave old selectors targeting elements that no longer exist.
- Use code search before renaming widely used classes.
- Keep related selectors together.
- Format long grouped selectors across multiple lines.
- Use consistent spacing around combinators.
- Use comments only when selector intent is not obvious.
- Avoid comments that merely repeat the selector.
- Test interaction pseudo-classes with a mouse.
- Test focus states with a keyboard.
- Test form state selectors with real controls.
- Test responsive interfaces on touch devices.
- Practice element selectors.
- Practice reusable class selectors.
- Practice unique ID selectors.
- Practice grouping selectors.
- Practice descendant and child selectors.
- Practice sibling selectors.
- Practice attribute selectors.
- Practice pseudo-classes.
- Practice pseudo-elements.
- Practice reading selectors from right to left conceptually when analyzing complex matching.
- Build small examples before using complex selectors in a large project.
- Use selector precision intentionally.
- Keep CSS predictable.
- Keep CSS maintainable.
- Learn selectors thoroughly before moving to advanced styling topics.
A good selector targets the intended elements without being unnecessarily broad, complex, or difficult to override.
Frequently Asked Questions
What is a CSS selector?
A CSS selector is a pattern used to identify HTML elements that should receive CSS declarations.
What is an element selector?
An element selector targets HTML elements by their tag name, such as p, h1, or button.
What is a class selector?
A class selector targets elements containing a specific class and begins with a dot, such as .card.
Can the same class be used on multiple elements?
Yes. Classes are designed to be reusable across multiple elements.
What is an ID selector?
An ID selector targets an element by its id value and begins with a hash symbol, such as #header.
Can the same ID be used multiple times?
An ID value should be unique within an HTML document.
What is the difference between a class and an ID?
A class is reusable across multiple elements, while an ID should uniquely identify one element in the document.
What does the universal selector do?
The * selector can match all elements.
How do I group multiple selectors?
Separate independent selectors with commas, such as h1, h2, h3.
What is a descendant selector?
A descendant selector uses a space to target matching elements anywhere inside another element.
What is a child selector?
A child selector uses > to target only direct children.
What is the difference between div p and div > p?
div p matches paragraph descendants at any depth inside a div, while div > p matches only paragraphs that are direct children of the div.
What does the + selector mean?
The adjacent sibling combinator targets the immediate next matching sibling.
What does the ~ selector mean?
The general sibling combinator targets matching siblings that appear later after another element.
What is an attribute selector?
An attribute selector targets elements according to the presence or value of an HTML attribute.
How do I target only email inputs?
You can use input[type="email"].
What is a pseudo-class?
A pseudo-class targets an element based on a state, condition, or structural position, such as :hover or :first-child.
What is a pseudo-element?
A pseudo-element targets a specific part of an element or a generated box, such as ::first-letter or ::before.
What is the difference between :hover and ::before?
:hover is a pseudo-class representing an interaction state, while ::before is a pseudo-element that creates a styleable generated box before the element content.
Can selectors be combined?
Yes. Selectors can be combined to target elements more precisely.
What is specificity?
Specificity is one part of the CSS cascade used to compare competing selectors when declarations apply to the same element and property.
Which is generally more specific: class or element?
A class selector has greater specificity than an element selector.
Which is generally more specific: ID or class?
An ID selector has greater specificity than a class selector.
Does the most specific selector always win?
Not in every situation. Importance, origin, cascade layers, specificity, and source order can all affect the winning declaration.
Why is my selector not working?
Possible reasons include a spelling mistake, incorrect class or ID prefix, incorrect HTML structure, a selector that does not match, or another declaration winning in the cascade.
How can I debug selectors?
Use browser developer tools to inspect the element and review matched, overridden, and inherited CSS rules.
Should I use very long selectors?
Usually no. Shorter selectors are often easier to understand, reuse, and maintain.
What selector should beginners use most often?
Element selectors are useful for broad defaults, while class selectors are commonly used for reusable component styling.
What comes after CSS selectors?
The next lesson covers CSS colors and the different ways to define and apply colors.
Key Takeaways
- CSS selectors identify which HTML elements should receive styles.
- Selectors are written before declaration blocks.
- Element selectors target elements by tag name.
- Class selectors begin with a dot.
- Classes can be reused on multiple elements.
- ID selectors begin with a hash symbol.
- ID values should be unique within a document.
- The universal selector uses an asterisk.
- The universal selector can match all elements.
- Grouping selectors use commas.
- Grouping allows multiple selectors to share declarations.
- Combinators describe relationships between elements.
- A space creates a descendant selector.
- The descendant selector can match at any nesting depth.
- The > symbol creates a child selector.
- The child selector matches direct children only.
- The + symbol creates an adjacent sibling selector.
- The adjacent sibling selector targets the immediate next sibling.
- The ~ symbol creates a general sibling selector.
- The general sibling selector targets matching later siblings.
- Attribute selectors use square brackets.
- Attribute selectors can test attribute presence or values.
- Pseudo-classes usually begin with a single colon.
- Pseudo-classes target states and conditions.
- :hover targets an element during pointer hover.
- :focus targets an element that has focus.
- :checked targets checked form controls.
- Structural pseudo-classes target elements according to position.
- Pseudo-elements normally use two colons.
- Pseudo-elements can target parts of elements.
- ::before and ::after create generated boxes.
- Selectors can be combined for more precise targeting.
- .card h2 targets h2 elements inside .card.
- .card > h2 targets direct h2 children of .card.
- button.primary targets button elements with the primary class.
- Selector matching determines whether a CSS rule applies.
- Specificity helps compare competing selectors.
- Element selectors generally have lower specificity than class selectors.
- Class selectors generally have lower specificity than ID selectors.
- Specificity is only one part of the cascade.
- Source order can matter when competing declarations otherwise have equal priority.
- A valid declaration has no effect if its selector does not match.
- Overly complex selectors are difficult to maintain.
- Reusable classes are important for component styling.
- Browser developer tools help debug selector problems.
- Good selectors are precise, readable, and maintainable.
- Selectors are the foundation of controlling CSS styles.
Summary
CSS selectors determine which HTML elements receive styling declarations.
Element selectors target HTML tags, class selectors target reusable class values, and ID selectors target unique identifiers.
The universal selector can match all elements, while grouping selectors allow multiple independent selectors to share the same declarations.
Combinators allow elements to be selected according to their relationships in the HTML structure.
The descendant selector targets nested elements at any depth, while the child selector targets direct children only.
Adjacent and general sibling selectors target elements according to their sibling relationships.
Attribute selectors target elements according to HTML attributes and their values.
Pseudo-classes target states and conditions such as hover, focus, checked, and structural positions.
Pseudo-elements target specific parts of elements or create styleable generated boxes.
Selectors can be combined to create precise targeting patterns.
When multiple declarations compete for the same property, specificity can help determine the winner as part of the larger CSS cascade.
Good selectors should be precise enough to target the correct elements while remaining simple enough to understand and maintain.
In the next lesson, you will learn CSS colors and discover the different ways to add color to text, backgrounds, borders, and other visual elements.