Diging deeply about the absolute div's position inside relative div's position

The use case

When you code web too enough, you usually see the use case like a div inside the another div. Outer div has relative position and inner div is absolute position. Almost case, we will move the inner div to the position where we want to place around the outer div.

Explanation

When we move the inner div, almost dev thinks: the postion decided by the center of the div. It's wrong, the postion decided by the spacion from the edges of inner div to the edges of outer div

Example 1

You can see the code below

<div class="wrapper">
    <div class="square1">1</div>
    <div class="square2">2</div>
    <div class="square3">3</div>
    <div class="square4">4</div>
  </div>
/* Center input */
body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh
}

.wrapper {
  position: relative;
  width: 500px;
  height: 500px;
  border: 1px solid blue
}

.wrapper > div {
  position: absolute;
  width: 100px;
  height: 100px;
  border: 1px solid red;
}

.square1 {
  right: 100%;
  bottom: 100%;
}

.square2 {
  bottom: 100%;
  left: 100%;
}

.square3 {
  top: 100%;
  right: 100%;
}

.square4 {
  top: 100%;
  left: 100%;
}

Running the code you can see, four squares placed to four difference corners. Looking to the square1, the right and bottom of the inner div is 100%, it is mean the spacion from the right and bottom edge of inner div to outer div is 100% (exactly width/height of the outer div).

The square2, square3, square4 is same but place in the different position.

You can see the exmple through jsbin

Example 2

Assume we have a div can not edit code to move it, know the width and next to the line, the line always start from the inner div to end of the outer div. When we adjust the width of the outer div, the line will increase/ decrease too. It's responsive design.

By using the position we can decide the width and height, the point begin and end of the line.

<div class="wrapper">
  <div class="fixed-div">Fixed div, can not edit</div>
  <div class="line"></div>
</div>
.wrapper {
  width: 500px;
  height: 500px;
  border: 1px solid red;
  position: relative;
}

.fixed-div {
  position: absolute;
  top: 200px;
  left: 10px;
  width: 100px;
}

.line {
  position: absolute;
  background-color: blue;
  left: 100px;
  right: 0px;
  top: 210px;
  bottom: 289px;
}

It's is my jsbin, change the width of outer div you will see

The conclusion

In the example 1 we understood: the position not decided by the center the inner. And in the exmple 2 we can use the position to decide the width, height, point start point end of the inner div.

Comments

Contact for work:Skype
Code from my 💕