CSS Selectors
Learn how to target HTML elements with different types of selectors
🎯 What are CSS Selectors?
CSS selectors are patterns used to select and target HTML elements that you want to style. They tell the browser which elements to apply the CSS rules to.
/* Selector targets h1 elements */
h1 {
color: blue;
}
Types of CSS Selectors
Element Selector
Selects all elements of a specific type
p { color: red; }
ID Selector
Selects element with specific ID
#header { color: blue; }
Class Selector
Selects elements with specific class
.highlight { color: yellow; }
Universal Selector
Selects all elements on the page
* { margin: 0; }
🔹 Element Selector
The element selector targets all HTML elements of a specific type, applying styles universally across a site. For example, h1 { color: navy; } styles all top-level headings. It is the foundation of CSS, providing broad, consistent styling with low specificity. This selector is ideal for establishing base typography, spacing, and color schemes. It ensures visual consistency and reduces repetitive code. However, overuse can lead to unintended side effects, so it's often paired with more specific selectors in larger projects. Proper use of element selectors creates a solid, maintainable foundation for your CSS architecture, leading to faster load times and cleaner code—both favorable for SEO and overall site performance.
/* Selects all h1 elements */
h1 {
color: navy;
font-size: 28px;
}
/* Selects all paragraph elements */
p {
color: #333;
line-height: 1.6;
}
/* Selects all button elements */
button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
}
<h1>This heading will be navy</h1>
<p>This paragraph will be dark gray</p>
<button>This button will be green</button>
Result:
This heading will be navy
This paragraph will be dark gray
🔹 Class Selector
Class selectors target elements with a specific class attribute, prefixed by a period (e.g., .highlight). They allow reusable styling across different element types, promoting DRY (Don't Repeat Yourself) principles. Classes are ideal for component-based design, such as buttons, cards, or warning messages. They offer higher specificity than element selectors but lower than IDs, making them flexible for overriding. Using semantic class names (like .alert-warning) improves code maintainability and accessibility. Well-organized class-based CSS supports modular scaling, easier debugging, and efficient caching. This results in faster page loads and better Core Web Vitals—direct ranking factors for search engines—while enhancing developer workflow and long-term site maintainability.
/* Selects elements with class="highlight" */
.highlight {
background-color: yellow;
padding: 5px;
}
/* Selects elements with class="button" */
.button {
background-color: #007cba;
color: white;
padding: 12px 24px;
border-radius: 5px;
text-decoration: none;
}
/* Selects elements with class="warning" */
.warning {
color: #d32f2f;
font-weight: bold;
border-left: 4px solid #d32f2f;
padding-left: 10px;
}
<p class="highlight">This text is highlighted</p>
<a href="#" class="button">Button Link</a>
<p class="warning">This is a warning message</p>
Result:
🔹 ID Selector
ID selectors target a single, unique element with a specific id attribute, prefixed by a hash (e.g., #header). They have the highest specificity among basic selectors, making styles hard to override. IDs are best used for one-off page landmarks like #main-navigation or #contact-form. While useful for JavaScript hooks and anchor links, over-reliance in CSS can lead to specificity wars and reduced flexibility. For styling, classes are generally preferred. However, strategic ID use can provide clear, scoped styles for unique structural components. Proper ID usage contributes to a well-organized DOM, which aids search engine crawlers in understanding page structure and can support on-page SEO through clear content hierarchy.
/* Selects element with id="header" */
#header {
background-color: #2c3e50;
color: white;
padding: 20px;
text-align: center;
}
/* Selects element with id="main-content" */
#main-content {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
/* Selects element with id="footer" */
#footer {
background-color: #34495e;
color: white;
text-align: center;
padding: 15px;
}
<div id="header">Website Header</div>
<div id="main-content">Main content area</div>
<div id="footer">Website Footer</div>
Result:
🔹 Universal Selector
The universal selector (*) matches every element on the page, applying styles globally. It is commonly used in CSS resets or normalizations to remove default browser margins, paddings, and box-sizing inconsistencies. For example, * { margin: 0; padding: 0; box-sizing: border-box; } establishes a consistent baseline. However, it should be used sparingly due to performance considerations—it can slow down style calculation on very large pages. When applied thoughtfully, it simplifies cross-browser styling and creates a predictable layout foundation. A clean, consistent baseline improves rendering performance and accessibility, contributing to better Core Web Vitals scores and a more stable user experience, which are critical for SEO success.
/* Selects ALL elements */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* This is commonly used for CSS reset */
* {
font-family: Arial, sans-serif;
}
⚠️ Use with Caution:
The universal selector affects every element on your page, so use it carefully. It's commonly used for CSS resets to remove default browser styling.
🔹 Combining Selectors
Combining selectors increases specificity and precision by targeting elements based on multiple conditions, relationships, or attributes. Examples include descendant selectors (article p), child combinators (ul > li), and adjacent sibling selectors (h2 + p). Grouping selectors with commas applies the same rule to multiple elements efficiently. Attribute selectors like input[type="text"] offer fine-grained control. These techniques reduce the need for excessive classes, keep HTML clean, and enable powerful, context-aware styling. Well-structured combined selectors create maintainable, scalable CSS architectures that improve page load performance and enhance crawlability for search engines by reducing redundant code and improving semantic clarity.
🔸 Multiple Classes
/* Element must have BOTH classes */
.button.primary {
background-color: #007cba;
color: white;
}
.button.secondary {
background-color: #6c757d;
color: white;
}
<button class="button primary">Primary Button</button>
<button class="button secondary">Secondary Button</button>
🔸 Descendant Selector
/* Selects p elements inside div elements */
div p {
color: blue;
margin-left: 20px;
}
/* Selects links inside navigation */
nav a {
text-decoration: none;
color: #333;
}
<div>
<p>This paragraph is inside a div</p>
</div>
<p>This paragraph is NOT inside a div</p>
🔹 Selector Priority
Selector priority, or specificity, determines which CSS rule applies when multiple selectors target the same element. The cascade follows a clear hierarchy: !important overrides everything, followed by inline styles, then ID selectors, class/attribute/pseudo-class selectors, and finally element/pseudo-element selectors. Understanding this order is crucial for debugging style conflicts and maintaining predictable stylesheets. Avoiding overly specific selectors and !important keeps CSS manageable. A disciplined approach to specificity leads to cleaner, more maintainable code, faster rendering performance, and fewer unexpected visual bugs. This technical excellence supports better SEO outcomes through improved site stability, faster load times, and a smoother user experience across all devices.
Priority Order (highest to lowest):
- Inline styles - style="color: red;"
- IDs - #header
- Classes - .highlight
- Elements - p, h1, div
/* Element selector - lowest priority */
p {
color: black;
}
/* Class selector - higher priority */
.special {
color: blue;
}
/* ID selector - highest priority */
#unique {
color: red;
}
<p>Black text</p>
<p class="special">Blue text</p>
<p id="unique" class="special">Red text (ID wins)</p>