CSS Box Model & Layout Basics
What Is the CSS Box Model?
Every HTML element is a rectangle box that follows this model:
+---------------------------+
| margin |
| +---------------------+ |
| | border | |
| | +-------------+ | |
| | | padding | | |
| | | +--------+ | | |
| | | | content | | | |
| | | +--------+ | | |
| | +-------------+ | |
| +---------------------+ |
+---------------------------+Content → Padding → Border → Margin
box-sizing
Controls how width/height are calculated:
* {
box-sizing: border-box;
}content-box(default): width only includes content.border-box: includes content + padding + border.
✅ Use border-box for predictable layouts.
display Property
Defines how an element behaves in layout:
div {
display: block;
}
Common Values:
| Value | Description |
|---|---|
block | Full-width, breaks line |
inline | Flows inline with content |
inline-block | Like inline, but with width/height |
none | Hides the element |
flex | Flex container (layout) |
grid | Grid container |
position Property
Positions an element relative to something.
.box {
position: relative;
top: 10px;
left: 20px;
}| Value | Description |
|---|---|
static | Default, in normal flow |
relative | Positioned relative to itself |
absolute | Positioned relative to nearest non-static parent |
fixed | Positioned relative to viewport |
sticky | Scrolls until a threshold, then sticks |
Bonus: z-index
Controls stack order (works with position):
.modal {
position: absolute;
z-index: 999;
}Float and Clear
float
Makes element float left or right:
img {
float: right;
}clear
Prevents element from wrapping around floated items:
.clearfix {
clear: both;
}Modern Alternative:
Use Flexbox/Grid instead of float for layouts. Floats are now mostly for inline images or simple wrap effects.
overflow
Controls what happens when content overflows a box:
.box {
overflow: auto;
}| Value | Effect |
|---|---|
visible | Default, content spills out |
hidden | Extra content is clipped |
scroll | Always shows scrollbars |
auto | Shows scrollbars if needed |
You can also control x/y separately:
overflow-x: scroll;
overflow-y: hidden;🧪 Final Example
.container {
width: 300px;
padding: 1rem;
border: 2px solid #ccc;
margin: 1rem auto;
box-sizing: border-box;
overflow: auto;
}
img.float-left {
float: left;
margin-right: 1rem;
}
.card {
display: inline-block;
width: 45%;
position: relative;
top: 10px;
}✅ Recap of What You’ve Learned:
- Box Model (content → padding → border → margin)
box-sizingbest practicedisplay: block, inline, flex, gridposition: static, relative, absolute, fixed, stickyfloatandclearoverflow: control content clipping/scrolling
