css – difference between positioning and margin usage

Question:

Since I learned about positioning in css , the difference between padding with margin (1) and top\right\bottom\left (2) has been a mystery to me.

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

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

top: 0;
left: 0;

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

The question is when to use which tool?

Answer:

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 padding around each element, shifting the adjacent ones.

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

Scroll to Top