简体   繁体   English

尽管在样式表 - CSS中设置为0,但保证金仍然存在

[英]Margin exists despite being set to 0 in stylesheet - CSS

In Chrome when I open up Inspect Element on my webpage, I notice one of the divs has a margin on the right side that fills the rest of the page horizontally: 在Chrome浏览器中,当我在我的网页上打开Inspect Element时,我注意到其中一个div在右侧有一个边距,可以横向填充页面的其余部分:

注意右边距延伸到页面边缘

As far as I know, no right margin should exist on that div. 据我所知,该div上不应存在合适的保证金。 In the stylesheet of the html document, the right margin is set to zero. 在html文档的样式表中,右边距设置为零。 And, the box model in the Inspect Element window shows a right margin of - : 并且,Inspect Element窗口中的框模型显示了-的右边距:

CSS: 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;
}

Inspect Element: 检查元素:

HTML布局

Inspect Element框模型

What could be causing this right margin on the logo div? 什么可能导致logo div上的这个右边距?

If more information is required to determine what's happening, please tell me. 如果需要更多信息来确定发生了什么,请告诉我。

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) has an automatic right margin because it (normal div's) want to be 100% of the width of the parent div. 像div in-flow这样的块级元素(div是块级元素,而不是像span,img或strong这样的内联元素)具有自动右边距,因为它(普通div)想要100%父div的宽度。

Solutions are float:left (to get it out of flow), display:inline-block (to change its flow-abilities, as mentioned in the comments above, I'm not hogging credit :) ) and flexbox (which is relatively new so I wouldn't recommend jumping in on that just yet). 解决方案是浮动的:左(使其脱离流量),显示:内联块(改变其流动能力,如上面的评论所述,我不会赊帐:))和flexbox(这是相对较新的所以我不建议跳进去。)

Also, have a look at bootstrap and its grid system to get better aligning for your website which also scales beautifully to phones and tablets. 另外,看看bootstrap及其网格系统,以便更好地调整您的网站,这也可以很好地扩展到手机和平板电脑。

Minor addition: 次要补充:

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

with: 有:

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

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

creates an easy (but not responsive) centered solution 创建一个简单(但没有响应)的中心解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM