1. The CSS Rule Structure
A Cascading Style Sheet (CSS) is simply a collection of rules. Every rule consists of two main parts: the Selector and the Declaration Block.
| Part | Definition | Example |
| Selector | Specifies which HTML element(s) to style. | h1 |
| Declaration Block | Contains one or more declarations, enclosed in curly braces {}. | { color: blue; font-size: 24px; } |
| Declaration | A single Property-Value pair, terminated by a semicolon ;. | color: blue; |
| Property | The specific feature you want to change (e.g., color, width, font). | font-size |
| Value | The setting for that property. | 24px |
Example of a Complete CSS Rule:
p {
color: #333; /* Declaration 1: Sets text color to dark grey */
line-height: 1.5; /* Declaration 2: Sets vertical spacing */
}
2. Basic Selectors
Selectors are the most crucial part of CSS, determining which elements the styles apply to.
A. Type (Element) Selectors
These target all instances of a specific HTML element type.
/* Targets ALL <h1> elements on the page */
h1 {
text-align: center;
}
/* Targets ALL <img> elements */
img {
max-width: 100%;
}
B. Class Selectors
Classes are the most common and versatile way to apply styles. To use a class, you:
- Add the
classattribute to your HTML element (e.g.,<p class="alert">). - Precede the class name with a period (
.) in your CSS.
/* Targets all elements with class="warning" */
.warning {
border: 1px solid red;
background-color: yellow;
}
C. ID Selectors
IDs target a single, unique element on a page. You:
- Add the
idattribute to your HTML element (e.g.,<div id="main-nav">). - Precede the ID name with a hash symbol (
#) in your CSS.
/* Targets ONLY the element with id="logo" */
#logo {
float: left;
padding: 10px;
}
Best Practice: Use classes for styling and reuse. Reserve IDs for JavaScript targeting or fragment identifiers.
D. Universal Selector
The universal selector targets every single element on the page.
/* Targets every element and sets its margin and padding to zero */
* {
margin: 0;
padding: 0;
box-sizing: border-box; /* Crucial for box model consistency */
}
3. Combining Selectors
A. Grouping
You can apply the same styles to multiple selectors by separating them with a comma.
/* All <h1>, <h2>, AND elements with class="promo" will have this font */
h1, h2, .promo {
font-family: sans-serif;
letter-spacing: 2px;
}
B. Chaining
You can chain selectors together (with no space) to select an element that satisfies ALL the conditions simultaneously.
/* Targets ONLY <h1> elements that ALSO have the class="main-title" */
h1.main-title {
color: purple;
}
/* Targets ANY element that has BOTH class="card" AND class="active" */
.card.active {
background-color: lightblue;
}
