A CSS positioning trick
Good to know about the CSS position attribute
Here, we're going to look at a neat feature with CSS and the "position" attribute. It's one of features I appreciate the most when I'm creating DHTML scripts.
"position" is used to determine where elements should be placed on our web page. We have these values to choose from:
- static - Normal document flow. (Default if no positining is defined)
- relative - Relative to normal document flow.
- absolute - The element is taken out of the normal document flow and shown at the location specified by the CSS left and top attribute(or right and bottom).
- Fixed - Fixed position on the screen regardless of scrolling. (Not supported by Internet Explorer)
position:absolute
Many users with some CSS experience thinks that position:absolute always positions an element at a x,y distance from the top left corner of the browser. Example:
<div style="position:absolute;left:20px;top:50px">
should position this div 20 pixels from the left edge and 50 pixels from the top of the browser window.
Well, usually the div would be positioned there. But it doesn't have to.
If the parent element is positioned(relative or absolute), then the coordinates is determined from the top left corner of the parent element and not the top left corner of our browser window.
Example:
<DIV style="position:relative; width:100px;height:100px;border:1px solid #000;float:left">
<div style="position:absolute; left:20px;top:50px;width:10px;height:10px;background-color:red;"> </div>
</div>
This CSS will produce this result:
The small red "box" is positioned 20 pixels from the left and 50 pixels from the top left corner of the parent box. I have used this knowledge in many of my DHTML scripts. Example: Position the month and year drop downs in my calendar, close buttons in window scripts etc.
A little warning at the end
Be careful with position:absolute. It is extremely useful in many DHTML scripts, but it is often bad to use it too much for normal page layout. It would make it hard for you too modify the layout later.