Matthew Tipton Matthew Tipton - 2 months ago 6
CSS Question

Can't understand relative property of position

I'm learning CSS from basis and have done a small sample: https://jsfiddle.net/L290pjwb/

HTML part:

<div class = "a">A</div>
<div class = "b">B</div>
<div class = "b">B1</div>


CSS part:

div {
width : 50px;
height : 50px;
border : 1px solid black;
box-sizing : border-box;
}

.a {
position: static;
}

.b {
position : relative;
top : 10px;
left : 10px;
width : 100px;
height : 100px;
}


Boxes are located in such way:

enter image description here

All right, I understood, that
position: static
is the default position model for HTML elements and it can't be relocated just by adding the
top, bottom, right, left
properties.
position: relative
is like
static
, but offers some kind of
offset
, which
static
can't.

My question is: why isn't
B1
box located like this
:

enter image description here

?

Answer

Relative positioning places the element where it would be if it was statically positioned and then offsets it from that position without influencing anything else.

B is put where it would be normally and then offset. B1 is put where it would be normally (i.e. immediately after where B would be normally without positioning) and then offset.

You would only get this effect enter image description here if the static position for B1 was calculated from the offset position of B instead of the static position of B.

If you want to move elements about and have their new position influence the position of other elements: Use margins instead of relative positioning.

div {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  box-sizing: border-box;
}
.a {
  position: static;
}
.b {
  position: static;
  margin-top: 10px;
  margin-left: 10px;
  width: 100px;
  height: 100px;
}
.b + .b {
  margin-left: 20px;
}
<div class="a">A</div>
<div class="b">B</div>
<div class="b">B1</div>