differences in the use of positioning and margin

From the moment I learned about positioning in css, the difference between indenting with margin(1) and top\right\bottom\left(2) is a mystery to me.

In my view, these two attributes do the same thing, and the only difference I could find is that (1) refers to box-model, when (2) does not.

I also know about the application of (2) for "relativity of the sides", i.e. things like:

top: 0;
left: 0;

And then it will be "nailed" to the upper left the edge.

The question is when which tool to use?

Author: Silento, 2017-05-25

2 answers

To understand the difference, you need to try putting more than one element:

.m {
  margin: 10px;
}

.r {
  top: 10px;
  left: 10px;
  right: 10px;
  bottom: 10px;
  position: relative;
}

div { height: 30px; width: 30px; border: 1px solid #999; display: inline-block; }
body{ font-size: 0;}
span{ font-size:15px;}
<hr><span>без отсупов:</span>
<hr>
<div></div>
<div></div>
<div></div>
<hr><span>margin:</span>
<hr>
<div class="m"></div>
<div class="m"></div>
<div class="m"></div>
<hr> <span>top/left:</span>
<hr>
<div class="r"></div>
<div class="r"></div>
<div class="r"></div>
<hr>

You can see in the example that margin creates a real indent around each element, shifting the adjacent ones.

top/left it simply shifts the elements down and to the left, without affecting the layout in any way. In theory, top/left is more similar to transform: translate, with differences in hardware acceleration and relative units

 3
Author: Crantisz, 2017-05-25 12:45:39

I've always drawn rules for myself - on a piece of paper:

margin (внешний отступ) | padding (внутренний отступ): ↑ → ↓ ←;

Is well remembered. There are cases when margin will not be able to correct the situation of indentation from the frame and the text inside the frame will seem to stick, padding will come to the rescue, which will make an internal indent from the frame of the element.

 1
Author: And, 2017-05-25 13:31:45