Getting Down with ...

by ...

Lesson n:

Introduction to CSS Box Model

Each element in an HTML page defines a rectangular region the browser uses to place the element in the browser window. CSS has a collection of properties for formatting the rectangle around each element. Together these make up what is called the CSS box model.

The following diagram shows the properties of the box model and how they relate to each other:

CSS Box Model Diagram

The innermost box holds the HTML element's content. Between the box contents and the element border lies the padding. Padding size can be set on all four sides of the content. It inherits its color from the background-color property of the content. The margin lies outside the border and gets its color from the parent element.

The most effective way to understand all this is to practice with it, which we begin without delay.

Exercises:

  1. Download nested_boxes.html, then do each of the following to it:
    • Add the following declarations to the div#box1 style already in the style sheet:
          margin: 40px;
          padding: 40px;
          border: 10px solid #000;
          background-color: #F0F;
          
      Reload the page and note how it looks.
    • Now add a new style for div#box2 (put it directly below the div#box1 style) and add these declarations:
          margin: 40px;
          padding: 40px;
          border: 10px dotted #000;
          background-color: #FF0;
          
      Again reload the page and observe the changes.
    • Finally, see if you can add a style on your own for the last box that will make your resulting page look something like this.
  2. Download box_size.html, then do each of the following to it:
    • Add a new style for the div element (between the h1 and hr styles) with the following rules in in the declaration block:
          width: 500px;
          height: 200px;
          background-color: #F70;
          
      Reload the page and note how it looks.
    • Follow this with a style for div#box2 with the following rules:
          margin: 50px;
          padding: 50px;
          border: 10px solid #000;
          
      Reload and note the changes.
    • Add the following two class styles immediately below the p style that will set the width of the corresponding p and hr elements:
      .line1 {
          width: 500px;
      }
      .line2 {
          width: 720px;
      }
      
      Since paragraphs are already set to text-align: center;, setting the width will move text to the center of each hr element. Again reload the page and note how it looks. If all went well it should look something like this.
    • Explain why the total width of box 1 is only 500 pixels while box 2 has a total width of 720 pixels.