Box Model

All pages are made up of HTML elements that are contained within the box model.

 

It consists of:

  • margins, outside the border
  • borders
  • padding, inside the border
  • content, at the centre of the box

 

 

Values can be set using px, em or ex.

 

margin: Npx; border: Npx; or padding: Npx; on their own, will give equal values to all four sides.

 

 

Or to set individual values, use:

  • padding-top: Npx;
  • padding-right: Npx;
  • padding-bottom: Npx;
  • padding-left: Npx;
  • border-top: Npx;
  • border-right: Npx;
  • border-bottom: Npx;
  • border-left: Npx;
  • margin-top: Npx;
  • margin-right: Npx;
  • margin-bottom: Npx;
  • margin-left: Npx;

 

Shorthand examples:

  • 2 pairs (top/bottom same, left/right same): margin: 1ex 0.5em;
  • 3 values set top, left/right pair, bottom in order: padding: 2ex 1em 4ex;
  • 4 values Individually, in order TRBL: padding: 4ex 0.5em 5ex 3em;

 

Negative margins can be used to offset or move/extend margin or padding or content outside it’s box container

 

Width and Height of an Element
When setting the width and height properties of an element with CSS, you just set the width and height of the content area.

 

To calculate the full size of an element, you must also add the padding, borders and margins.

 

Given the following CSS for an element, the total width equates to 640px:

width:500px;
padding:20px;
border:30px solid red;
margin:20px;

 

This is calculated as follows:

500px (width)
+ 40px (left + right padding)
+ 60px (left + right border)
+ 40px (left + right margin)
= 640px

Save & refresh browser:

My first Heading

Paragraph one

Paragraph two

Paragraph three

Leave a Reply