CSS Selectors & Fundamentals
Cascading Style Sheets (CSS) controls the visual presentation, color scheme, and typography of your HTML markup. A CSS rule set consists of a selector pointing to HTML elements, followed by a declaration block containing property and value pairs.
Common CSS Selectors
To apply styles effectively, you must understand how selectors target elements:
- Element Selectors: Target tags directly by name (e.g.,
p,h1,button). These apply universally to every matching tag. - Class Selectors: Target elements sharing a
classattribute, prefixed with a dot (e.g.,.highlight,.card). Classes are reusable across multiple elements. - ID Selectors: Target a unique element by its
idattribute, prefixed with a hash (e.g.,#main-header). An ID must be unique within a single document.
/* Element selector */
p {
color: #334155;
font-size: 16px;
}
/* Class selector */
.callout {
background-color: #f1f5f9;
border-left: 4px solid #2563eb;
padding: 12px;
}
/* ID selector */
#main-nav {
background-color: #0f172a;
}
Understanding Specificity
When multiple CSS rules conflict on the same element, the browser resolves the conflict using specificity:
- Inline styles written in the HTML tag take highest priority.
- ID selectors carry high weight.
- Class, attribute, and pseudo-class selectors carry medium weight.
- Element and pseudo-element selectors carry the lowest weight.
As a best practice, prefer class selectors for styling. Overusing ID selectors makes your stylesheet rigid and difficult to maintain.
Key takeaways
- CSS declarations consist of properties and values wrapped inside curly brackets.
- Use element selectors for baseline typography defaults.
- Use class selectors (
.class-name) for reusable component styles. - Keep specificity low and balanced by relying primarily on classes rather than IDs.