Previous Page
Next Page

Positioning Absolutely

Before CSS, if you wanted something in a precise place in a browser window, you had to do some tricky table work and keep your fingers crossed that it would work cross-browser. Script 11.9 shows how you can instead use CSS to tell your browser to put things just where you want them.

In this example, we've decided to swap the two images (the play folio and Shakespeare). Rather than messing around with the HTML, we'll just make changes to two of the CSS rules, the ones for body (for the background image of the playwright) and img (for the folio). You can specify precisely where you want the items to appear on the page, as in Figure 11.9.

Script 11.9. By changing the body and img rules, we've changed the look of the page.

body {
     background-color: white;
     color: black;
     font-family: "Trebuchet MS", verdana, helvetica, arial, sans-serif;
     font-size: 0.9em;
     background-image: url(images/shakespeare.gif);
     background-repeat: no-repeat;
     background-position: 20px 80px;
}
img {
     position: absolute;
     top: 20px;
     right: 20px;
}
.character {
     font-weight: bold;
     text-transform: uppercase;
}
div.character {
     margin: 1.5em 0em 1em 17em;
}
.directions {
     font-style: italic;
}
.dialog, .directions {
     margin-left: 22em;
}
.directions .character {
     font-size: 1.4em;
}
#week2 {
     background-color: #FFFF00;
}
a {
     text-decoration: none;
     padding: 5px 10px 5px 10px;
}
a:link {
     color: #0000FF;
}
a:visited {
     color: #000000;
}
a:hover {
     color: #FFFFFF;
     background-color: #000000;
     text-decoration: underline;
}
a:active {
     color: #FF0000;
}

Figure 11.9. Swapping the position of the two images required no fiddling with the HTML page, just a few changes to the CSS style sheet.


To use absolute positioning:

1.
background-position: 20px 80px;



This property is within the body rule and tells the browser to put the picture of Shakespeare 20 pixels from the left edge of the window and 80 pixels down from the top of the window. In other words, the first value is the horizontal position and the second value is the vertical.

2.
img {
  position: absolute;
  top: 20px;
  right: 20px;
}



These changes to the img rule are straightforward. First, we specify that the position is absolute, meaning that it will be precisely specified by the top, right (and if needed, bottom and left) properties. Then we follow that with the values for top and right, again in pixels measured from the top-left corner of the page.

Tip

  • If there were multiple images on the page, we could specify exactly which one we wanted to change by instead using an id (to specify a particular image; remember that ids are unique on a page) versus the img tag itself.



Previous Page
Next Page