Setting Relative Element to Specific Other Element?

When setting an Element to “Relative”, how do I go about choosing what it’s positioned relative to?

  • Studio2B

When positioning an element as relative its new position is relative to itself. Se let’s say you specify left: 20px to a relative positioned element. This element will be displaced 20px to the right from its original position.

To make it a little more clear I can add to Matthias’ answer that you should think of an element with relative position as having the possibility to move it around relatively from the original elements’ place on the page (if you don’t specify any placement changes like “left” or “top” your element will just stay where it is in the layout flow, same as if you have left it with “static” positioning).

@mrmtta and @dram - So if setting an Element to “Relative” only allows you to move it from it’s original position, what would be the advantages (or disadvantages) to using “Relative” for an Element, instead of simply using a Transform for that same Element, and simply moving it up/down/left/right by doing it that way? I’m sure the first thing you should always do would be to attempt to accomplish the same result using Margins or Padding, but when that’s not possible, again why not use Transforms instead of “Relative”? What makes it so magical? EG: In what situation would you use “Relative” instead of a Transform?

The main usage for “position:relative” is to define the position of a children element with “position:absolute” -> if you position any element with a value of absolute, it will look up into its parent elements until it finds one with position set to relative. So, top, left, top, and bottom values of the element with “position:absolute”, will be relative to the first parent with a “position” set to “relative”.

Position:relative is also used to set the z-index attribute of an element, allowing you to specify which elements sit on top of others when having overlapping content.

Of course you can also use position:relative to “break” the normal position of an element. If you use transform or position:relative is up to you. You should go with the approach that makes more sense to the way you structure your layout. There is no bad or good. Also, be aware that transform is way more powerful than just moving an element in the Y and X axis.