admin管理员组

文章数量:1122832

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>

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>

Share Improve this question edited Nov 21, 2024 at 19:30 Nadirspam asked Nov 21, 2024 at 18:56 NadirspamNadirspam 18910 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 3

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

In this case, it's because you set the div's width to 100%. Try setting it to auto.

* {
  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>

本文标签: htmlcss marginleft vs marginright behaviorStack Overflow