Difference between the margin of box and relative position


#1

In the class I learn to use relative position with top bottom left right direction. But I feel like its function is the same as the margin.
What’s the difference between them?


#2

To clarify, those are not directions but boundaries. The value we give to those properties is the offset.

Consider,

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>offset</title>
    <style>
      div {
        position: relative;
        top: 20px;
        left: 30px;
        height: 300px;
        border: 1px solid gray;
      }
    </style>
  </head>
  <body>
    <div></div>
  </body>
</html>

Save and run this in your browser. It won’t look like much. A box that extends all the way off the screen to the right, with a left offset of 30px, so you can see the ‘margin’, as it were. Had we set a predetermined value for a parent container, we would see the box overflow that containers border by the offset amount of the top, 20px. I’ll set up a different view while you examine this one.

Note, that the box size does not change. It started out as 100% in width, and is now hanging off the screen by 30px, the offset amount. Offsets do not affect the box size. Margins, on the other hand do. In the style rule above, change left: 30px; to margin-left: 30px; and refresh. Notice how it does not flow off the screen. The box just gets smaller to accomodate the margin.


#3

As promised, I would come back with another representation

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Relative Offset</title>
    <style>
      div {
        position: relative;
        width: 300px;
        height: 300px;
        border: 2px solid gray;
      }
      div div {
        top: 20px;
        left: 30px;
        border-color: darkBlue;
      }
    </style>
  </head>
  <body>
    <div>
      <div></div>
    </div>
  </body>
</html>

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.