Position Absolute (Just for knowledge)
Another way to position elements on the page is with absolute positioning. You can use position: absolute to place elements anywhere on the page.
Absolute positioning removes an element out of the normal, static flow. Other elements will move up to fill its place. The element you have just removed from the normal flow is now like a free-standing element. (The borders of the removed element shrink to fit the contents. If you want more space you have to specify it with width and height properties.)
Items that are given an absolute position are placed in relation to their parent element. If no parent element exists then the default is the HTML tag. To illustrate what this means, take a look at the image below:
Here, we've placed a paragraph of text at the top, followed by two images, one below the other.
Now take a look at the HTML code:
The paragraph of text has an inline style setting its border to green. We then have two sets of DIV tags. The red ones are the outer DIV tags. Think of these as the parent tags. Inside the parent DIV tags are two inner DIV tags, the blue ones. For each set of DIV tags we have an image.
However, if we were to set the blue rectangle to have a top position of 0, what do you think would happen? Where would it move to? Well, take a look at the CSS code with just position: absolute:
The first thing we've done is to set values for the HTML and BODY tags. We've set the margin to 10 pixels and the padding to 0. This is just so that you can see the images more clearly.
For the relative positioning, we've commented out position: relative. You'll see why in a moment. For the absolute position, we've commented out the top value of zero. The question is, if we take out the comments for top: 0px where will the blue rectangle end up? Here's what happens in the browser when we do just that:
The blue rectangle jumps right to the top of the browser window. The reason is does so is that its parent element, the outer DIV, has no position set. In which case, the position: absolute of the inner DIV tags uses the HTML tag as a parent. So the browser window is now top: 0px.
When we take the comments out for position: relative, however, here's what happens:
The top: 0px position is now using the outer DIV as a parent. The blue rectangle can't move up any further than this, so it covers up the pink rectangle - it's placed on top of it.
This is all quite complicated. So just bear in mind that when using absolute positioning, you have to take the parent element into account. If you don't set a parent element that uses the position CSS property then the HTML tag is used.
No comments:
Post a Comment