CSS Selectors & Box Model
What you'll learn: How to target specific HTML elements with CSS and understand the spacing system that controls every element's size and layout.
CSS Selectors: Targeting Your HTML
Think of CSS selectors as addresses that tell the browser exactly which HTML elements to style. You've already learned HTML structure—now you need to reach into that structure and apply styles precisely.
Three fundamental selectors:
- Element selector: Targets all elements of a type →
p { color: blue; }styles all paragraphs - Class selector: Targets elements with a specific class →
.highlight { background: yellow; }styles any element withclass="highlight" - ID selector: Targets one unique element →
#header { font-size: 24px; }styles the element withid="header"
Classes are reusable (use them often), while IDs should be unique on a page.
The Box Model: Every Element is a Box
Here's the crucial insight: every HTML element is a rectangular box with four layers of space around its content.
Imagine packing a gift:
- Content = the gift itself (your text/image)
- Padding = bubble wrap directly around the gift (space inside the border)
- Border = the box edges (visible line around the element)
- Margin = space between your box and other boxes on the shelf (space outside the border)
.card {
padding: 20px; /* Space inside the border */
border: 2px solid black; /* The border itself */
margin: 10px; /* Space outside, pushing other elements away */
}
Padding makes the element bigger inside, while margin pushes other elements away.
Key Takeaway: CSS selectors let you precisely target HTML elements, and the box model (content → padding → border → margin) controls how every element takes up space on the page.