CSS: the box model, backgrounds and positioning

Lesson 6 of 17 · HTML, CSS and JavaScript

For the browser every element is a rectangle: content, inner spacing, a border and outer spacing. Once you understand this "box model", you know why elements move apart, how cards and buttons are made and how to place an element exactly where you want it.

Before you start: required prior knowledge – CSS basics.
How to learn: do the tasks at the end on your own in your editor first; open the hint and the solution only after that. Every example has the code and a live result below it; type the code into your own file and change it.

The parts of the box

┌───────────── margin (outer spacing) ──────────────┐
│  ┌─────────── border ──────────────────────────┐  │
│  │  ┌──────── padding (inner spacing) ───────┐  │  │
│  │  │                                        │  │  │
│  │  │        content                         │  │  │
│  │  │        width × height                  │  │  │
│  │  └────────────────────────────────────────┘  │  │
│  └──────────────────────────────────────────────┘  │
└────────────────────────────────────────────────────┘
<style>
  .box {
    width: 220px;
    padding: 20px;                 /* inside: from the text to the border */
    border: 4px solid #2b7bb9;     /* thickness, style, colour */
    margin: 16px;                  /* outside: from the border to neighbouring elements */
    background: #eef6fc;
  }
</style>
<div class="box">Box 1</div>
<div class="box">Box 2</div>

Result:

NotationMeaning
padding: 10px;the same on all four sides
padding: 10px 20px;10 at the top and bottom, 20 on the left and right
padding: 5px 10px 15px 20px;top, right, bottom, left (clockwise)
margin: 0 auto;a block element with a set width becomes centred
padding-top, margin-left…one side only

box-sizing: how wide an element really is

By the default rule width is the width of the content only, so the box in the example is 220 + 2·20 + 2·4 = 268px wide. This is confusing, which is why almost every site writes at the start of its CSS:

*, *::before, *::after {
  box-sizing: border-box;   /* width includes the padding and the border */
}

With border-box, a box with width: 220px is exactly 220px wide, and 220 − 40 − 8 = 172px is left for the content.

Borders, shadows and backgrounds – a card example

<style>
  * { box-sizing: border-box; }
  body { background: #f2f4f7; }
  .card {
    max-width: 280px;
    background: white;
    border-radius: 12px;                        /* rounded corners */
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);    /* shadow: x y blur colour */
    padding: 16px;
    margin: 10px auto;
  }
  .card h3 { margin-top: 0; }
  .button {
    display: inline-block;
    padding: 8px 16px;
    background: linear-gradient(90deg, #2b7bb9, #1f5f91);   /* a colour gradient */
    color: white;
    border-radius: 999px;
    text-decoration: none;
  }
  .button:hover { opacity: 0.85; }
</style>
<div class="card">
  <h3>HTML and CSS course</h3>
  <p>10 lessons, examples and exercises for primary school students.</p>
  <a class="button" href="#">Start</a>
</div>

Result:

PropertyExample
border-radius8px; 50% turns a square into a circle
box-shadow0 2px 6px rgba(0,0,0,.2)
background-colorthe background colour
background-imageurl("images/background.jpg") or linear-gradient(...)
background-size: coverthe image covers the whole element
max-widththe largest width – on a narrower screen the element shrinks

display: block, inline, inline-block, none

ValueBehaviour
blocka new line, the full width, accepts width/height (div, p, h1)
inlinein the line with the text, ignores width/height (a, span, strong)
inline-blockin the line, but accepts width, height and padding – buttons, badges
nonethe element is not shown and takes no space (used with JavaScript for hiding)
flex, gridarranging the children – the next lesson

Positioning

<style>
  .frame  { position: relative; height: 140px; background: #eef6fc; border: 1px dashed #2b7bb9; }
  .badge  { position: absolute; top: 8px; right: 8px; background: crimson; color: white; padding: 4px 10px; border-radius: 999px; }
  .nudged { position: relative; left: 30px; top: 10px; background: #fff3cd; display: inline-block; padding: 4px; }
</style>
<div class="frame">
  <span class="badge">NEW</span>
  <span class="nudged">moved 30px to the right and 10px down</span>
</div>

Result:

positionBehaviour
staticthe default – the element is in its place in the flow of the page
relativemoved relative to its own place (top, left…); also serves as an "anchor" for absolute children
absolutetaken out of the flow and placed relative to the nearest positioned parent – badges, labels on images
fixedstuck to the window, it does not move when you scroll – a "back to top" button
stickybehaves normally until it reaches the edge, then it sticks – table headers, menus

To lay out whole parts of a page you do not use position, but flexbox and grid.

Practice tasks

Each task has an example, a hint and a solution. The solutions have been checked in the browser.

TASK 01Difficulty: medium

A profile card

Make a profile card at most 300px wide, centred on the page: a round 100×100 image, a name, a short description and a "Follow" button. The card has a white background, rounded corners and a shadow, and the page has a grey background.

Common mistakes and tips
  • Without box-sizing: border-box the padding and the border increase the set width.
  • margin: auto centres only a block element that has a width (width or max-width).
  • Width and height do not work on inline elements (a, span) – give them display: inline-block.
  • The outer margins of two blocks one above the other are not added up – the larger one is used.

Check your knowledge

Open the quiz

The box model

1. Which part of the box is between the content and the border?




2. How wide is a box with width: 200px, padding: 10px, border: 2px without border-box?




3. How is a block element with a set width centred?




4. Which position value stays in the same place on the screen when you scroll?