CSS Positions

Positions are a very basic yet confusing part of CSS. In this article we'll understand various CSS positions and how do they work. Let's get started !!!

Static Position

By default all the elements in HTML have position set to Static

1.png

position: static is not mentioned most of the times as it is defined by default. It just tells the browser to put the element in the normal position without changing any property. As shown in the image above the all the elements are in their default position. The positioning properties like top, bottom, left, right do not work with position static. Most basic stuff.

Now, let's move to the exciting stuff. Let's talk about Relative Positioning

.child {
position: relative
position: absolute 
position: fixed
}

Relative positioning are of three type as shown above.

1. position: relative

.child1 {
    position: relative;
    top: 20px;
    left: 20px;
}

image.png

as we can see the first box is moved 20px from top and left, it shows that it is has moved relative to its normal/original position and the space that it was taking up doesn’t change, so it won’t affect anything around it.

2. position: absolute

.child1 {
    position: absolute;
    top: 20px;
    left: 20px;
}

image.png

Box 1 has moved 20px from top and left but unlike position: relative, the space that was occupied initially by the box 1 is taken by the neighbouring elements, leaving no empty space.

In position: absolute the element moves relative to it's parent element (the parent should have relative or absolute position in order to have child element move with respect to parent)

3. position: fixed

.child2 {
    position: absolute;
    top: 200px;
    left: 200px;
}

image.png

Box 2 moved 200px from top and left with respect to viewport. Viewport is basically the visible area of webpage.

So when the position: fixed is given the object will set its position with respect to the page and this means even if the page is scrolled the element will remain at set position.

In position: fixed also similar to position: absolute, the space that was occupied initially by the box 2 is taken by the neighbouring elements, leaving no empty space.

  • Now the question arises that what is the difference between position: absolute and position: fixed ?

In position: absolute the position of element is changed with respect to the parent element which has position relative or absolute and in position: fixed the position of element is changed with respect to the viewport.

Hope you find this article useful and it added some understanding about positions in CSS.