The CSS Box Model

every web page element is in a box with a standard structure

an element’s box is a rectangle with some of these features

  • the outer “ring” of the box is the margin, sometimes called the outer margin; a box has a top, bottom, left, and right margin

    if two boxes are touching each other, then the distance between them is set to be the max of their margins (not their sum); this is known as margin collapsing

  • just inside of the margin is the border; a box has a top, bottom, left, and right border; you can also set the width, color, and style of a border

  • just inside of the border is the padding, sometimes called the inner margin; a box has top, bottom, left, and right padding

  • inside of the padding “ring” is where the body content of the element goes

  • the width and height properties of the box refer to the width and height of this body content rectangle

  • there’s an overflow rule that tells the box what to do if the content inside of the box is too big for it; the most common overflow rules are

    • auto, if there is too much content, the overflowing content is hidden and scroll bars are shown to let the user scroll to see all the content
    • hidden, if there is too much content, the overflowing content is hidden
    • visible, If there is too much content, the overflowing content is shown outside of the box; this is usually the default behavior

box’s have other properties (such as background clips and outlines) that we won’t go into here

Kinds of CSS Boxes

there are three main kinds of element boxes

  • block is a box that where adjacent boxes are put on new lines before/after the box; for example, h and p are block boxes; the width and height of block boxes can be changed
  • inline boxes flow with the text, and setting their width/height has no affect
  • inline-block combine properties of both block and inline boxes, e.g. inline-block boxes flow with the text but can have their width and height changed