Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

position: relative

Overview

To design and under­stand the page lay­outs, we need to under­stand the posi­tion prop­erty in css. An ele­ment is said to be posi­tioned, when its posi­tion attribute is set.

 position : relative || absolute || fixed || sticky (experimental);

The default value for the posi­tion attribute is sta­tic.

This post is one of the posts in the series of posts to under­stand the posi­tion attribute in css. Make sure to read all of them to fully under­stand the posi­tion attribute.

An ele­ment on DOM can be cat­e­go­rized in one of the fol­low­ing categories :

  • posi­tion : sta­tic || rel­a­tive — ele­ment is in the nor­mal doc­u­ment flow.
  • posi­tion : absolute || fixed — ele­ment is absolutely positioned.
  • float : left || right — ele­ment is float­ing. Learn More about floats.

Get­ting started

If we do not apply any posi­tion to the squares then they are ren­dered in the nor­mal doc­u­ment flow, mean­ing the green square is ren­dered to the next avail­able space after the red square. In the below pen, we have three col­ored square div ele­ments, which have the default (sta­tic) posi­tion. Hence, they are ren­dered in the nor­mal doc­u­ment flow.

See the Pen relative-1 by Kavit Shah (@kavitshah8) on Code­Pen.


If will apply, the posi­tion: rel­a­tive to the red square, then it will be a posi­tioned ele­ment. It will allow us to off­set the ele­ment. The below pen off­sets the red square from top by 30px and left by 70px;

See the Pen relative-2 by Kavit Shah (@kavitshah8) on Code­Pen.


Notes on offset

  • Pos­i­tive off­set value moves an ele­ment away from the edge, apply­ing ‘left: 20px’ moves an ele­ment 20px away from the edge towards right and vice versa.
  • Off­set does not remove an ele­ment from its nor­mal doc­u­ment flow, which is very dif­fer­ent than the floated element.
  • In the above exam­ple, off­set­ting the red square did not remove it from its orig­i­nal place. Hence, the green square could not occupy its position.
  • But if we increase the dimen­sions of the red square then we can see the posi­tion of the green square changes as shown in the below pen.

See the Pen relative-3 by Kavit Shah (@kavitshah8) on Code­Pen.


Check out James Williamson’s excel­lent tuto­r­ial on Rel­a­tive Positioning !

Most com­mon use cases for position:relative

  • To tweak the lay­outs. For exam­ple, to off­set an element.
  • It’s also used to apply posi­tion to con­tainer ele­ments which allows us to apply posi­tion: absolute to the child elements.

Fur­ther reading


You may also like...