Interpreting values in margin parameter


I am doing the "CSS Positioning->Margin top, right, bottom, left" section. In experimenting with the margin values, it seems to me that only the top and left values really seem to decide the position of the div block. For example I experimented with the following:

margin: 20px 20px 10px 5px;` OR
margin: 20px -20px 10px 5px;

Expecting the div block to move to the right but it remained in the same position.

  1. What space is the margin parameter defining? It seems like it is defining space between screen border and margin edge.

  2. also it seems like what matters is top and left margin setting.

The only way that makes sense is if I consider that the px values are respectively moving the screen edge away from the div block by that value.


Not entirely, everything is based (drawn) relative to the top left side side of your screen, this doesn't mean margin-bottom and margin-right have no affect, take a look at this simple example, as you can see, margin-bottom does have an effect (i actually assume the code is pretty self explaining), you can see margin beautiful by right clicking on the div, and select something like: inspect element/source code (depending on your browser, search for the box-model, and example in for firefox:

a while ago (quit a while actually) i wrote this answer, i hope it can give you some insight, if you have any further questions, do ask, this is a very important part. I hope this at least improves your understanding. Margin is pushing things around, starting in the top left corner.


Try to see if you can set two divs side by side (hint: give both a float: left property and width less than half the screen, say 40%).

Give the div on the left a negative right margin, and the div on the right a 0 left margin. What happens with the div on the right? Does it overlap the div on the left?

Right margin determines how far away a neighboring object to the right will be.

        <div class="left"></div>
        <div class="right"></div>


.left, .right {
    float: left;
    width: 40%;
    height: 100px;
    margin: 10px 0 0 0;
    border: 2px solid black;
.left { margin-right: -20px;}