Friday, 30 May 2008

CSS: Absolutely Positioned DIV (AP)

#blue {
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
background-color: blue;
}

Listing 1: Defining an Absolutely Positioned div

Let's take a look at the above code line by line.

  1. #blue - The # in front of our selector declares that this is an ID selector
  2. width: 100px; - The div will be 100px wide
  3. height: 100px; - The div will be 100px high
  4. position: absolute; - The div will be absolutely positioned in accordance to the top and left property values
  5. top: 0; - The div will be positioned 0 units from the top edge of the browser viewport
  6. left: 0; - The div will be positioned 0 units from the left edge of the browser viewport
  7. background-color: blue; - The background colour of the div will be blue

I have given our div a height value. It is often a good idea to not declare a height for your div so it can expand and contract to suit the content it may hold. Content could fluctuate due to text resizing by the end user, or you may be using your div for dynamic data that varies from record to record. These are two examples of instances where a height declaration may be a problem.

Once the positioning value has been declared as absolute, it is removed from the flow of the page. An absolutely positioned div will remain in the position it is placed—in accordance with its top and left property values—within its containing element. You can think of an AP div as being on a higher plane than page level. They act as if they are stacked above the page.

http://www.communitymx.com/content/article.cfm?cid=3B56F

No comments: