Every HTML element on a web page is a box. The CSS Box Model describes how this box is built: content, padding, border, and margin. Understanding the Box Model is crucial for controlling the size and distribution of elements.
The width and height properties define the size of the content, while
box-sizing determines whether padding and border are included in those dimensions. The
overflow property solves the problem when content exceeds the size of an element.
Positioning determines where an element is located on the page. There are five positioning
methods: static (default), relative, absolute, fixed, and
sticky. With the z-index property, we control which element is in the foreground when
elements overlap.
| Property | Example | Description |
|---|---|---|
| Box Model: Size | ||
width | width: 300px; |
Sets the width of the element content |
height | height: 200px; |
Sets the height of the element content |
min-width | min-width: 200px; |
Minimum allowed width |
max-width | max-width: 100%; |
Maximum allowed width |
min-height | min-height: 100px; |
Minimum allowed height |
max-height | max-height: 500px; |
Maximum allowed height |
box-sizing | box-sizing: border-box; |
Includes padding and border in total width/height (recommended!) |
| Box Model: Overflow | ||
overflow | overflow: hidden; |
What to do when content overflows the element (visible, hidden, scroll, auto) |
overflow-x | overflow-x: scroll; |
Overflow in horizontal direction only |
overflow-y | overflow-y: auto; |
Overflow in vertical direction only |
| Positioning | ||
position: static | position: static; |
Default – element follows the normal flow of the page |
position: relative | position: relative; top: 10px; |
Moves the element relative to its default position |
position: absolute | position: absolute; top: 0; right: 0; |
Positions the element relative to its nearest positioned ancestor |
position: fixed | position: fixed; bottom: 0; |
Attaches the element to the browser window (does not move on scroll) |
position: sticky | position: sticky; top: 0; |
Combination of relative and fixed – sticks when it reaches a specified position |
top / right / bottom / left | top: 20px; left: 50px; |
Sets offset from edges (only works with position: relative/absolute/fixed/sticky) |
| Stacking (Z-Index) | ||
z-index | z-index: 100; |
Sets the stacking order (higher value = more in front) |
| Floating (Float) | ||
float | float: left; |
Element floats left or right (left, right, none) |
clear | clear: both; |
Prevents element from floating next to a previous float element |