正文后面的 div 仅在 Firefox 中导致较大的上边距

问题描述 投票:0回答:6

我已经查看了以前的答案,但它们都与浮动元素等页面相关。这是一个简单的页面,有一个

h1
p
元素:

<body>
    <div class="title">
        <h1 id = "main_title">Chocolate Eclairs</h1>
    </div>
    <div class="main">
        <p>A simple french treat.</p>
    </div>
</body>

CSS(为了清晰起见):

body{   background-color: pink; margin: 0; }
h1{ background-color: blue;}
.main{ background-color: white;}

这会在页面顶部产生一个间隙,并且

body
不是从顶部开始。

Starting with a div 如果我注释掉第一个

div
元素,使其首先以
h1
开头,它就会消失:

Starting without a div

那么,我该如何解决这个问题?我的页面依赖于以 div 元素开头,而 firefox (26.0) 是唯一生成此内容的浏览器。

html css firefox
6个回答
2
投票

您已经被怪异模式崩溃的利润所困扰。在某些情况下(在标准中详细阐述),子元素的边距(在本例中为

h1
)将转移到封闭元素。但是,您的文档没有
DOCTYPE
,因此浏览器会进入怪异模式,并非所有规则都会得到遵守。看来在这种情况下 Firefox 仍然遵守该规则,但其他人可能不会。

解决办法是

  1. 在文件顶部添加适当的

    DOCTYPE

    <!DOCTYPE html>
    
  2. 添加规则以删除边距

    h1

    h1 { margin: 0; }
    

1
投票

使用这个css,只需在h1样式中添加一个margin:0px

body{   background-color: pink; margin: 0; }
h1{ background-color: blue;margin:0px}
.main{ background-color: white;}

并且DEMO在这里


1
投票

您看到的是元素上的默认样式。你需要看看 css 重置,一个流行的重置是 Eric Meyer 的重置

/* http://meyerweb.com/eric/tools/css/reset/ 
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

通常我所做的就是在样式表顶部添加类似的内容。

* {
  margin:0;
  padding:0;

 /* A better box model */
 -webkit-box-sizing:border-box;
 -moz-box-sizing:border-box;
  box-sizing:border-box;
}

选择所有元素,并删除边距和填充。还使用 box-sizing:border-box。这是一个更直观的 CSS 盒子模型。填充和边框不会添加到元素的实际设置宽度中。 您可以通过保罗·爱尔兰阅读更多内容。


0
投票

尝试将与body相同的样式设置为html:

html,body{   background-color: pink; margin: 0; }

0
投票

伙计们,我找到了这个问题的解决方案,这很简单请确保 和 margin:0px; 之间有一个空格;在体内的特性会起作用,所以


-2
投票

默认情况下,标题标签 H1、H2 等具有上边距。 Firefox 中的上边距未正确包含。

尝试 h1{padding:0;margin:0} 来调试问题。然后用padding-top来代替margin-top。

我建议您不要使用重置表。它们有副作用。

© www.soinside.com 2019 - 2024. All rights reserved.