PBS - CSS Positioning Playground

Part of the Programming by Stealth Series by Bart Busschots

Getting Started

When you press the start buttom below, a new window will pop up containing five boxes, a red one, a green one, a blue one, a yellow one, and a magenta one. The red, green, and blue boxes are top-level <div> tags, added to the HTML document in that order. The yellow and magenta boxes are both <div> tags contained within the green box, the yellow one first, then the magenta one.

When you press the start button a control panel will also appear below, allowing you to see and edit the CSS properties for each of the five boxes in the popup window. The controls are colour-coded to show which box they control. As you change the values in the control panel, the boxes will update appropriately in the popup window, and, as you re-size the popup window, the values in the control panel will update too.

You will have to allow the popup through your popup blocker for this demo to work.

Control Panel

Tip

To build the two-column layout with header and footer as shown in the demo at the end of PBS instalment 8, take the steps below. Box 1 will be used at the header, box 2 simply contains the middle parts of the page, with box 4 being the main content, and box 5 becoming the side bar. Finally, box 3 will be the footer.

  1. Create some space to move the side-bar into by setting the left margin of box 4 to 140px. This value is the sum of the width we will set the side-bar to (100px) and twice the 20px margins in use around all the boxes.
  2. Set the width of box 5 to 100px.
  3. Set the position of box 5 to absolute. Notice that it has now been pulled out of the normal flow of the document, causing box 2 to shrink, and hence box 3 to move up.
  4. Set the top and left of box 5 to 0px. Because this box is not contained within any positioned boxes, its position has been calculated relative to the body of the page. Because it has a 20 pixel margin, the visible part of the box now appears 20 pixels down from the top of the body, and 20 pixels in from its left - over box 1.
  5. To make the positioning of the sidebar (box 5) be relative to the central region (box 2), we need to turn that box into a positioned box by setting its position to something other than static that will not pull it out of the normal flow, nor alter its placement within the document - set the position of box 2 to relative