[英]Unwanted top margin for h1 element
I am getting an unwanted top margin for an h1 element, not sure why.我得到了一个 h1 元素的不需要的上边距,不知道为什么。 This is my html:这是我的 html:
<body>
<div class="content">
<h1>Header</h1>
<p>Paragraph 1.</p>
<p>Paragraph 2.</p>
<p>Paragraph 3.</p>
</div>
</body>
This is my css:这是我的 css:
body {
background-color: yellow;
padding: 0px;
margin: 0px;
}
h1 {
background-color: lime;
}
.content {
background-color: pink;
position: absolute;
left: 0px;
top: 0px;
padding: 0px;
margin: 0px;
}
the result:结果:
I was expecting the h1 element to be aligned with the top edge of the view.我期待 h1 元素与视图的顶部边缘对齐。
If I remove the "position", "left" and "top" attributes from the css def, then the h1 element aligns to the top of the view as expected:如果我从 css def 中删除“位置”、“左”和“顶部”属性,则 h1 元素将按预期对齐到视图的顶部:
why is that happening?为什么会这样? I'm using chrome.我正在使用铬。
Thanks谢谢
You need to add margin:0;
您需要添加margin:0;
: :
h1 {
margin:0;
background-color: lime;
}
JSFiddle: http://jsfiddle.net/tb39am7s/ JSFiddle: http : //jsfiddle.net/tb39am7s/
For every element browser itself sets the default styles. 浏览器本身会为每个元素设置默认样式。 That includes headings, which get some margin at top and bottom - you need to remove them by yourself in case you do not need them. 其中包括标题,标题的顶部和底部都有一定的余量-如果您不需要它们,则需要自己删除它们。
Unfortunally, those default styles differ from browser to browser, even if W3C gives recommendation , that is why developers try to reset default styles or normalize it before they start adding their own. 不幸的是,即使W3C给出了建议 ,这些默认样式也会因浏览器而异,这就是为什么开发人员尝试在开始添加自己的默认样式之前对其进行重置或对其进行规范化的原因 。 There is difference between previous two . 前两者之间有区别 。
Remove top margin on your h1: 移除h1的上边距:
http://jsfiddle.net/austinthedeveloper/wwzxn8gx/ http://jsfiddle.net/austinthedeveloper/wwzxn8gx/
h1 {
background-color: lime;
margin-top: 0;
}
h1 elements have a default margin. h1元素具有默认边距。 Adding margin: 0;
加margin: 0;
to your h1 properties should clear up your margin issue. 到您的h1物业应清除您的保证金问题。 I believe that the margin is based on the element that contains it. 我认为保证金是基于包含它的元素。
<div class="container">
<h1>HEADER</h1>
</div>
//style
div.container{
padding: 0;
}
h1{
margin-top: 0;
}
Also you coudl use normalize.css to reset the default values of some tags. 同样,您可以使用normalize.css重置某些标签的默认值。 http://necolas.github.io/normalize.css/ http://necolas.github.io/normalize.css/
this happens because of default h1 "line height".这是因为默认的 h1“行高”。 you can add line-height property with any desired value like this:您可以添加任何所需值的 line-height 属性,如下所示:
h1{
line-height: 1em;
}
如果您使用position: absolute
确保在父元素上指定position: relative
,它应相对于(在您的情况下为<body>
),看看是否有帮助。
You can do: 你可以做:
h1{
margin:0
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.