ArM
ArM

Reputation: 307

CSS position:relative - why are top and bottom not cancelling each other?

I just started learning CSS. My understanding of position:relative may be wrong... but I assumed that:

  1. top - moves element towards the bottom
  2. bottom - moves element towards the top
  3. left - moves element towards the right
  4. right - moves element towards the left

So, I tried the code given below (copied from w3schools), to see if equal values of top/bottom/left/right would effectively cancel out the individual movements, and keep the element in it's original position, but it didn't work. The element seems to have moved to the 'bottom right' of it's original position.

What exactly is happening here? Is there a reason these movements aren't being cancelled out? Here's the same code on JSFiddle, along with the output.

div.relative {
  position: relative;
  top: 30px;
  right: 30px;
  bottom: 30px;
  left: 30px;
  border: 3px solid #73AD21;
}
<h2>position: relative;</h2>
<p>An element with position: relative; is positioned relative to its normal position:</p>
<div class="relative">This div element has position: relative;</div>
<p>abcd</p>

Upvotes: 1

Views: 288

Answers (3)

web-tiki
web-tiki

Reputation: 103750

First of all, the statements 1,2,3 and 4 are false because you can specify negative values for top, right left and bottom. So top/bottom move the element on the X axis and Left/right can move it on the Y axis.

Second, you can read for relative positionning :

If neither 'left' nor 'right' is 'auto', the position is over-constrained, and one of them has to be ignored. If the 'direction' property of the containing block is 'ltr', the value of 'left' wins and 'right' becomes -'left'. [...]

[source: w3.org section 9.4.3 ]

This means that the left property takes precedence over the right property in the defautl direction (ltr). It is the same for top and bottom with top taking precedence over bottom.

Upvotes: 4

El0din
El0din

Reputation: 3370

For relatively positioned elements, the top property sets the top edge of an element to a unit above/below its normal position.

The problem is that the top is taking the div, and the bottom is including the <h2> and the <p>.

Upvotes: 0

Eakethet
Eakethet

Reputation: 682

Well, it takes the last parameter given in horizontal and vertical position. So in your case it is "bottom" and "left".

Upvotes: -2

Related Questions