Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the CSS position on a div affects position of sibling division?

Tags:

html

css

I have been going through CSS Positions articles on Alistapart. Below snippet caught my attention and couldn't fathom the theory behind.

Below html/css shows two boxes one over other. But if I change the position of #box_1 to absolute, then #box_2 overlap #box_1.

<!DOCTYPE html >
<html lang="en">
<head>
    <style>
        #box_1 { 
            position: relative;
            width: 200px;
            height: 200px;
            background: #ee3e64;
        }
        #box_2 { 
            position: absolute;
            width: 200px;
            height: 200px;
            background: #44accf;
        }
    </style>
</head>
<body>
    <div id="box_1"></div>
    <div id="box_2"></div>
</body>
</html>
  1. How does the position of another box (box_1) affects position of a different/sibling div(box_2). Isn't 'absolute' should always absolute only to immediate non-static parent?

  2. In the above css (with "position: relative;" in box_1), if I add "top: 0;" to #box_2, then box_2 appears to overlap again. Why does this happens?

like image 712
Dbob Avatar asked Oct 06 '22 01:10

Dbob


1 Answers

An absolutely-positioned element will remain in its static position if you don't specify any of its top, right, bottom or left properties, regardless of whether any of its ancestors is positioned. That's why nothing appears to happen to #box_2 when you simply set it to position: absolute — instead, it's affected by #box_1 in the same way as if you hadn't specified position: absolute.

However, note that #box_1 affects #box_2 only because 1 precedes 2; once you absolutely position #box_2 it is taken out of the flow and any siblings that follow it will flow as if #box_2 was no longer there. See this example where I create a #box_3 that's identical to #box_1 and add it after #box_2, in which #box_3 overlaps #box_2 because 3 doesn't see 2 in the normal flow; it only sees 1.

Once you set top: 0 to #box_2, then it knows it has to be attached to the top of the viewport (as its containing block since none of its ancestors are positioned).

like image 173
BoltClock Avatar answered Oct 09 '22 11:10

BoltClock