将HTML中DIV标签定位到绝对顶部

3
.myDiv  
{

background-image: url(urltomyimgheader);

height:100px;

margin: auto;

position:relative;

top:-10px;

width:600px;

}

这是一个简单的div标签,用于显示logo...

我将其顶部位置向上移动了-10px,以使其与浏览器顶部接触,否则会在logo和页面之间留下空隙。

然而,我对使用-10px来定位div感到不满 :( 是否有更好且跨浏览器兼容的解决方案?

2个回答

3

@Tatu Ulmanen是对的,这是浏览器默认问题。您不需要添加负边距,只需设置body/html标记的默认CSS属性即可。

为了安全起见,您应该使用CSS重置来消除浏览器样式默认值。以下是可以解决您问题的代码。在此之后,您可以将以下很好的CSS重置添加到所有CSS样式表的顶部。

html, body {
padding: 0;
margin: 0;
}

CSS重置: /* 重置 */
    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, font, img, ins, kbd, q, s, samp,
    small, strike, strong, sub, sup, tt, var,
    dl, dt, dd, ol, ul, li,
    fieldset, form, label, legend,
    table, caption, tbody, tfoot, thead, tr, th, td
                        { margin: 0; padding: 0; border: 0; outline: 0; font-weight: inherit; font-style: inherit; font-size: 100%; font-family: inherit; vertical-align: baseline; }
    blockquote:before,
    blockquote:after,
    q:before, q:after   { content: ""; }
    blockquote, q       { quotes: "" ""; }
    body                { line-height: 1; color: black; background: white; }
    caption, th, td     { text-align: left; font-weight: normal; }
    :focus              { outline: 0; }
    table               { border-collapse: separate; border-spacing: 0; }
    ol, ul              { list-style: none; }

非常感谢! :) 从未想过重置样式表如此重要 :) - Ranhiru Jude Cooray

1

是的,10像素的间隙是由浏览器对某些元素默认填充而生成的。

body {
   padding: 0;
}

你可能还想了解CSS重置样式表,以重置所有元素的浏览器特定设置。这里有一个不错的选择


谢谢 Tatu :) 我已经多次看到了重置样式表,但直到现在我才知道它的重要性 :) - Ranhiru Jude Cooray

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接