Then when you view the sidebar in the browser, it is in the top right of the window. The book goes on to explain that an element is positioned relative to its parent’s element’s position. In this case, the sidebar does not have a parent element so the viewport is the positioning context.
Then it goes on to say that there is an elelment that can be positioned to provide us with a useful positioning context-the div with the id=“main”, which was already in the style sheet.
It says to add the following (which is the first 4 lines–margin-top was already there) to the main id:
Because of the added declarations (regarding position, top left, width) it makes #main as the parent of the #sidebar and I don’t understand why that is. Can anyone tell me please?
As far as positioning is concerned the parent of an element is the nearest ancestor with a positioned defined (other than static - i.e. relative or absolute). If no such ancestor exists then the viewport is the parent for the stacking context.
What this means is that if you have an absolutely placed child element then you can set the parent to position:relative and then the parent is the starting point for that absolute child’s positioning context. If the parent is moved then the absolute child is also moved in conjunction with the parent.
You could also set the parent to position:absolute but that would remove it from the flow and likely break the display. Adding position:relative without co-ordinates changes nothing to the flow of the document other than provide a positional context for its absolute children.
In your example the left:0 and top:0 settings for #main are redundant and should be removed. If you move the element by nothing then it has moved nowhere so the zeros are not needed.
Thanks, so basically, it is the declaration setting the parent’s (#main) position to relative that makes this work?
Go ahead and play with this some more: make a page with the same doctype, head, etc… but in the body, put a box in there (give it large top and left margins so it’s away from the edge, and then give it a child, and go around positioning the two of them and see how they do it. Then go add someone i between: make the first box a grandparent, and the original child a grandchild.