skip to Main Content

Assuming my body has background color of green,
when I do margin-left to my Div I can see the margin in a different color (green) and an overflow, but when I do margin-rigt the behavior is different, I see no margin nor overflow. Is there an explanation or reason fro it?

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: greenyellow;
}

.myDiv {
  width: 100%;
  height: 50px;
  background-color: rgb(112, 112, 0);
  /**margin-left: 50px;*/
  margin-right: 50px; 
}
<body>
  <div class="myDiv"></div>
</body>

2

Answers


  1. From the specification:

    If all of the above have a computed value other than ‘auto’, the values are said to be "over-constrained" and one of the used values will have to be different from its computed value. If the ‘direction’ property of the containing block has the value ‘ltr’, the specified value of ‘margin-right’ is ignored and the value is calculated so as to make the equality true. If the value of ‘direction’ is ‘rtl’, this happens to ‘margin-left’ instead.

    Note the direction which is very important and the default one is left-to-right ltr

    Login or Signup to reply.
  2. In this case, it’s because you set the div’s width to 100%. Try setting it to auto.

    Screenshot (margins fixed)

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      background-color: greenyellow;
    }
    
    .myDiv {
      width: auto;
      height: 50px;
      background-color: rgb(112, 112, 0);
      margin-left: 50px;
      margin-right: 50px;
    }
    <body>
      <div class="myDiv"></div>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search