【问题标题】:Strange CSS Behaviour, white space on top of body奇怪的 CSS 行为,主体顶部的空白
【发布时间】:2013-06-23 20:31:16
【问题描述】:

我的网站中有这样一个 DOM:

<html>
    <body>
        <div id='topbar'/>
        <div id='centerframe'/>
    </body>
</html>

使用 css 规则:

html
{
    margin:0;
    padding:0;
}

body
{

    background:url('/images/brickwall.jpg'); background-size: 10%;
    width:100%; 
    height:100%;
    margin:0;
    padding-top:0;
}

div#centerframe
{

    background:rgba(255, 255, 255, 0.85);
    box-shadow:0em 0.5em 2em 0.3em;
    padding:90px;
    margin-left:        180px;
    margin-right:       160px;  
    margin-top:         200px; /* this also causes body to slide down 200px , when body{padding-top:0} . why ? */

}

#topbar
{
    position:fixed;
    display:block;
    float:left;
    width:100%;
    height:80px;
    top:0;
    margin-top:0%;
    background:rgba(0,0,0,1);
}

这个 css 导致了这样一个问题:body 在顶部有一个边距,即使我告诉它 margin:0; 这是屏幕截图:

但是当我更改 css 并生成 body{padding-top: 1px;}(而不是 0)时,它可以正常工作。查看屏幕截图:

当我添加这条规则时它也可以工作:#centerframe{float:left;} 但它会导致其他问题,例如扩展到超过 100% 的宽度。

不管怎样,我用 1px 填充解决了这个问题。但为什么一开始就有问题呢?

&lt;body/&gt; 的子级如何更改其上边距?

谢谢!

【问题讨论】:

    标签: html css margin padding


    【解决方案1】:

    您的问题是由margin collapse 引起的,因为浏览器如何处理包括您显示的图像在内的后续元素。这可以通过您添加填充来证明,但我尚未对此进行测试。

    请注意,在您的示例中,&lt;div /&gt; 无效。 div 不会自动关闭。

    【讨论】:

      【解决方案2】:

      我未能在 jsFiddle 中重新创建此行为,因此我无法具体说明。不知道是不是浏览器的问题?

      你的 body 肯定没有边距,因为 topbar 总是在最顶部,所以那是你的 body 开始的地方。也许只是背景被取代了(出于某种尴尬的原因)。你玩过 background-position 属性吗?

      【讨论】:

        猜你喜欢
        • 2010-11-05
        • 2014-02-10
        • 2011-11-27
        • 1970-01-01
        • 1970-01-01
        • 2011-11-07
        • 1970-01-01
        • 2011-11-10
        • 2013-10-04
        相关资源
        最近更新 更多