How does the CSS position on a div affect the separation position of a sister?

I went through articles with CSS positions in Alistapart . Below the fragment caught my attention and could not understand the theory.

Below html / css two fields are shown one by one. But if I changed the position of # box_1 to absolute, then # box_2 overlaps # 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>
  • How the position of another block (box_1) affects the position of the other / div / div (div_2). Should not the โ€œabsoluteโ€ always be absolute only for the immediate non-static parent?

  • In the css above (with "position: relative;" in box_1), if I add "top: 0;" # box_2, then box_2 seems to overlap again. Why is this happening?

+5
source share
2 answers

, top, right, bottom left, , - . #box_2, position: absolute - #box_1 , position: absolute.

, #box_1 #box_2 , 1 2; , #box_2, , , #box_2 . . , #box_3, #box_1 #box_2, #box_3 #box_2, 3 2 ; 1.

top: 0 #box_2, , ( , ).

+4

CSS div sibling, . :

HTML:

  <div id="parent_1">
     <div id="child_1"></div>
     <div id="child_2"></div>
  </div>

CSS

  #parent_1{ 
        position: relative;
        width: 400px;
        height: 400px;
        background: gray;
    }
 #child_1 {
    position: absolute;
    left:20px;
    top:20px;
    width:40px; 
    background:yellow;
 }
#child_2 {
    position: absolute;
    right:20px;
    top:20px;
    width:40px; 
    background:blue;
 }

# parent_1 400 * 400 # child_1 div 20px 20px .

0

All Articles