Basic Selectors
Overview
Selectors are the grappling hooks of CSS. They allow you to target specific HTML elements to apply styles to them. The three foundational selectors are the Type selector (targets elements by their tag name), the Class selector (targets elements by their class attribute), and the ID selector (targets a single unique element by its id attribute). Mastering these is step one of writing maintainable stylesheets.
Syntax
/* 1. Type (Element) Selector: Targets EVERY <p> tag */
p {
line-height: 1.5;
}
/* 2. Class Selector (Prefix with a dot '.'): Targets specific groups */
/* In HTML: <button class="btn-primary"> */
.btn-primary {
background-color: blue;
color: white;
}
/* 3. ID Selector (Prefix with a hash '#'): Targets one UNIQUE element */
/* In HTML: <nav id="main-navigation"> */
#main-navigation {
position: fixed;
top: 0;
}Common Pitfalls
- Using ID selectors (
#header) for styling. IDs are extremely rigid and have incredibly high specificity, making them nearly impossible to override later in your CSS. Best practice dictates using IDs strictly for JavaScript hooks or Anchor Links, and using Classes exclusively for CSS styling. - Starting a class name with a number (e.g.,
.1st-place { color: gold; }). This is invalid syntax in CSS; class names must start with a letter, an underscore, or a hyphen.
Interview Questions
A Class (.) can be reused on infinite elements across the page to apply shared styles. An ID (#) is strictly unique and must only be used on exactly one element per HTML document.
Real-World Example
Applying multiple classes to a single HTML element to compose complex UI components (similar to Tailwind).
/* The structural base class */
.btn {
padding: 10px 20px;
border-radius: 8px;
}
/* The visual modifier class */
.btn-danger {
background-color: red;
}
<!-- HTML utilizes both classes simultaneously -->
<button class="btn btn-danger">Delete Account</button>Check Your Knowledge
Test your understanding of Basic Selectors with these quick questions.