左边和右边的保证金只显示在左边[重复]

时间:2022-04-18 09:29:42

This question already has an answer here:

这个问题在这里已有答案:

I'm trying to put a left and right margin on something that is also 100% width. It seems to put both the left and the right margin on the left size (totaling 200px on the left and not 100px either side. What is the reason for this?

我试图将左右边距放在也是100%宽度的东西上。似乎左边和右边都放在左边的尺寸上(左边总共200px而不是100px左边。这是什么原因?

It's demonstrated here:

它在这里展示:

http://jsbin.com/xomocitono/1

<div id="main">
  Test
</div>

#main {width: 100%; margin-left: 100px; margin-right: 100px; background: red;}

Thank you!

3 个解决方案

#1


2  

You can use calc for subtracting margin calc(100% - 200px);

您可以使用calc来减去保证金计算(100% - 200px);

https://developer.mozilla.org/en-US/docs/Web/CSS/calc

Support IE9 +

支持IE9 +

#main {
  width: calc(100% - 200px);
  margin-left: 100px;
  margin-right: 100px;
  background: red;
}
<div id="main">
  Test
</div>

Or you can just simply remove width

或者你可以简单地删除宽度

#main {
  margin-left: 100px;
  margin-right: 100px;
  background: red;
}
<div id="main">
  Test
</div>

#2


0  

Actually it happens bcoz you have given width to div as 100%

实际上它发生bcoz你给div的宽度为100%

Just remove that width you will get proper output

只需移除该宽度即可获得正确的输出

replace your css with this one

用这个替换你的CSS

#main {
margin-left: 100px;
margin-right: 100px;
background: red;
}

#3


0  

The div is already 100%. Put only the margins. http://jsfiddle.net/0df0emjc/

div已经100%了。只放置边距。 http://jsfiddle.net/0df0emjc/

<div id="main">
  Test
</div>
#main {
    margin:0 100px 0 100px;
    background: red;
}

#1


2  

You can use calc for subtracting margin calc(100% - 200px);

您可以使用calc来减去保证金计算(100% - 200px);

https://developer.mozilla.org/en-US/docs/Web/CSS/calc

Support IE9 +

支持IE9 +

#main {
  width: calc(100% - 200px);
  margin-left: 100px;
  margin-right: 100px;
  background: red;
}
<div id="main">
  Test
</div>

Or you can just simply remove width

或者你可以简单地删除宽度

#main {
  margin-left: 100px;
  margin-right: 100px;
  background: red;
}
<div id="main">
  Test
</div>

#2


0  

Actually it happens bcoz you have given width to div as 100%

实际上它发生bcoz你给div的宽度为100%

Just remove that width you will get proper output

只需移除该宽度即可获得正确的输出

replace your css with this one

用这个替换你的CSS

#main {
margin-left: 100px;
margin-right: 100px;
background: red;
}

#3


0  

The div is already 100%. Put only the margins. http://jsfiddle.net/0df0emjc/

div已经100%了。只放置边距。 http://jsfiddle.net/0df0emjc/

<div id="main">
  Test
</div>
#main {
    margin:0 100px 0 100px;
    background: red;
}