【问题标题】:Margin of main container set to 0 yet there is still a margin主容器的边距设置为 0 但仍有边距
【发布时间】:2016-04-08 14:52:15
【问题描述】:

我尝试了没有做任何事情的 css 样式表重置,以及其他解决方案,但没有修复。容器上的边距设置为 0,右侧仍有边距。如果我禁用左边距 0 额外的空白出现在左侧。提前致谢。

body {
  padding-top: 50px;
}
.container {
  overflow: hidden;
  margin-left: 0 auto;
  margin-right: 0 auto;
  padding: 0 0 0 0;
}
#content {
  overflow: auto;
  background-color: #FFFFFF;
  margin-left: 0;
  margin-right: 0;
}
#content-left {
  color: #FFFFFF;
  float: left;
  background-color: #666666;
  width: 30%;
}
#content-right {
  color: #FFFFFF;
  float: right;
  background-color: #333333;
  width: 70%;
}
<body>
  <div class="container" id="main">
    <div id="content">
      <div id="content-left">
        <div>LEFT</div>

      </div>
      <div id="content-right">
        <div>RIGHT</div>

      </div>

    </div>
  </div>

</body>

【问题讨论】:

  • 给定的代码工作得很好。 jsfiddle.net/w53Lorh9 可能是您的其他样式导致了问题。
  • width: 100% 添加到您的.container
  • 您的 .container 样式有问题...您使用了 margin-left: 0 auto;这是错误的.. margin-left: 0;或左边距:自动;是正确的..你不能一次使用 0 auto with margin-left...

标签: css margin


【解决方案1】:

将所有元素的边距设置为0px,这将删除多余的边距

* {
  margin: 0px;
}

还将width: 100% 添加到您的.container

注意:将此添加为 CSS 中的第一个样式。这可以被下面指定的样式覆盖。

以下是您的代码更新。

* {
  margin: 0px;
}
body {
  padding-top: 50px;
}
.container {
  width: 100%;
  overflow: hidden;
  margin-left: 0 auto;
  margin-right: 0 auto;
  padding: 0 0 0 0;
}
#content {
  overflow: auto;
  background-color: #FFFFFF;
  margin-left: 0;
  margin-right: 0;
}
#content-left {
  color: #FFFFFF;
  float: left;
  background-color: #666666;
  width: 30%;
}
#content-right {
  color: #FFFFFF;
  float: right;
  background-color: #333333;
  width: 70%;
}
<body>
  <div class="container" id="main">
    <div id="content">
      <div id="content-left">
        <div>LEFT</div>

      </div>
      <div id="content-right">
        <div>RIGHT</div>

      </div>

    </div>
  </div>
</body>

【讨论】:

  • * { 边距:0px; } 这会给他当前的风格带来问题。
  • @Alok : 这可以被下面指定的样式覆盖。
【解决方案2】:

将#content div 的宽度设置为 100% 将解决您的问题。这不是保证金问题。要让宽度 % 作用于内部 div,它需要一个容器宽度作为基础。

#content{
    overflow: auto;
    background-color:#FFFFFF;
    margin-left: 0;
    margin-right: 0;
    width: 100%;
}

【讨论】:

  • 你是对的,但是将其更改为内容并不能解决问题,我不得不将其更改为 (.container),因为它是整个 div,谢谢。