My Development Notes

Programming Made Easier


The concept of position : absolute and position : relative in CSS

Let me first type in the basic HTML and CSS files like so, and then I’ll explain this in detail (you’ll need to follow along to understand it fully well) :

<body>
    <div class="boxA">
        <div class="boxB">
            <div class="boxC"></div>
        </div>
    </div>
</body>
.boxA {
    width: 700px;
    height: 700px;
    background-color: antiquewhite;
}

.boxB {
    width: 600px;
    height: 600px;
    background-color: aquamarine;
}

.boxC {
    width: 500px;
    height: 500px;
    background-color: aqua;
}

So, we’ve created three basic boxes (boxA, boxB & boxC) one inside the other, as parent and child. Render the code and observe the default position of those boxes carefully. You’ll see that the boxes seem to stack on top of each other from the left margin.

Now let’s add the code below and see what happens :

.boxA, .boxB, .boxC {
    display: flex;
    justify-content: center;
    align-items: center;
}

In the above code we’ve added the basic flexbox properties and aligned the boxes to the center.

Now let’s add the position: absolute property and play along:

.boxC {
    position: absolute;
    top: 40px;
    left: 40px;
}

Now you’ll see that the boxC, even if it’s the child div of boxB, breaks off the boundary and places itself along it’s own independent lines as per the top and left margins typed in.

So, what position : absolute does is that it will position itself relative to the immediate parent (or ancestor) element (or div), boxB in this case.

Now instead of the above code, try this and see what happens:

.boxB {
    position: absolute;
    top: 0px;
    left: 0px;
}

It carries boxB and also the child div inside and positions itself relative to boxA, which is the immediate parent in this case.

Now let’s delete the code above and see how the relative positioning works in CSS. Add in the below code now:

.boxC {
    position: relative;
    top: 150px;
    left: 150px;
}

You will see from the above code that the boxC moves only relative to it’s own original position, not depending upon any other ancestor elements or divs.

So, the elements in case of position : relative, moves only relative to it’s own original position, not depending upon any other parents, divs or ancestors. So, that’s the ultimate difference between absolute and relative positioning.

Not clear yet? Go back to the last code block and instead of relative, type absolute and render it! Do this once or twice. Maybe change the top and left from 150px to something else.

I hope you got it now!


Posted

in

by

Tags:

Leave a Reply