Sunday, September 4, 2011

Woking with position:absolute in CSS

position:absolute is really nice when we are positioning some div through CSS. But we need to understand how to use it properly. When we add position:absolute we also need to take care of its behaviour. Just adding this does not make any difference, then we also need to add margin or directly(top, right, bottom and left) positions.

Adding top, right, bottom or left floats the entire div and works like a layer. It may overlap on some other div. So we need to add some px or em to make it float on the right position.
For Example: {position : absolute; top:100px; z-index:2}
When we added top:100px it took right from the body top. Even if we place this div at the bottom of the layout it will still float the top after leaving 100px.
This is usually used for popups.

Now about the margin.
margin will keep the div where it is embedded in the layout. It will never make div to float anywhere.
For Example{position:absolute; margin:100px 0 0 0}
This will keep the div at its place. only it will make it leave 100px at the top of his position. nothing else.

Working together with both(margin and direct positioning)
Mostly when we need to take any div to the center, we can use position:absolute.
As in my previous post we saw how to add popup.
We used
#hiddendiv{
  position:absolute;
  background: #fff;
  top:50%;
  left:50%;
  margin: -100px 0 0 -200px;
  width: 400px;
  height: 200px;
  border: 4px solid #CB6D23}
Here we can see from top:50% and left:50%. So the div will float 50% of each side we want. Then in margin I added in negative the half of its height for top and half of its width from left. This pulls the div to top and left half-half of its height and width and make it to the center of the layout.

No comments:

Post a Comment