尽管在样式表中设置为 0,边距仍然存在 - CSS

Margin exists despite being set to 0 in stylesheet - CSS

在 Chrome 中,当我在我的网页上打开 Inspect Element 时,我注意到其中一个 div 的右侧有一个边距,水平填充了页面的其余部分:

据我所知,div 上不应存在右边距。在 html 文档的样式表中,右边距设置为零。并且,Inspect Element window 中的框模型显示右边距 -:

CSS:

* {
    box-sizing: border-box;
}

body {
    margin: 0;
    padding: 0;
    background-color: #FFF;
}

#header {
    /*this is the parent div of the div with the unexpected right margin*/
    width: 100%;
    height: 50px;
    background-color: #26519E;
    box-shadow: 0 5px 5px Lightgray;
}

#logo {
    /*this is the div with the unexpected margin*/
    width: 120px;
    height: inherit;
    margin-left: 180px;
    /*!!!*/
    margin-right: 0;
    padding: 10px;
}

检查元素:

是什么导致 logo div 上的右边距?

如果需要更多信息来确定发生了什么,请告诉我。

A block-level element like a div in-flow (A div is a block-level element, not an inline element like a span, img or strong) 具有自动权限边距,因为它(正常 div's)想要成为父 div.

宽度的 100%

解决方案是float:left(让它脱离流动),display:inline-block(改变它的流动能力,正如上面评论中提到的,我不是在独占信用: ) ) 和 flexbox(这是相对较新的,所以我不建议立即加入)。

此外,请查看 bootstrap 及其网格系统,以便更好地对齐您的网站,该网站也可以很好地扩展到手机和平板电脑。

次要补充:

<div id="header">
  <div class="container">
  </div>
</div>
<div id="main">
  <div class="container">
  </div>
</div>

与:

#header,#main {
  width: 100%;
}
#header {
  background: brown;
  height: 3em;
}

.container {
  width: 1000px;
  margin: 0 auto;
  min-height: 20em;
}

创建一个简单的(但不是响应式的)中心解决方案