CSS Box Model & Layout Basics

ADVERTISEMENT

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:

ValueDescription
blockFull-width, breaks line
inlineFlows inline with content
inline-blockLike inline, but with width/height
noneHides the element
flexFlex container (layout)
gridGrid container

position Property

Positions an element relative to something.

.box {
  position: relative;
  top: 10px;
  left: 20px;
}
ValueDescription
staticDefault, in normal flow
relativePositioned relative to itself
absolutePositioned relative to nearest non-static parent
fixedPositioned relative to viewport
stickyScrolls 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;
}
ValueEffect
visibleDefault, content spills out
hiddenExtra content is clipped
scrollAlways shows scrollbars
autoShows 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-sizing best practice
  • display: block, inline, flex, grid
  • position: static, relative, absolute, fixed, sticky
  • float and clear
  • overflow: control content clipping/scrolling

ADVERTISEMENT