I am getting an unwanted top margin for an h1 element, not sure why. This is my 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:
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.
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:
why is that happening? I'm using chrome.
Thanks
You need to add margin:0;
:
h1 {
margin:0;
background-color: lime;
}
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. There is difference between previous two .
Remove top margin on your h1:
http://jsfiddle.net/austinthedeveloper/wwzxn8gx/
h1 {
background-color: lime;
margin-top: 0;
}
h1 elements have a default margin. Adding margin: 0;
to your h1 properties should clear up your margin issue. 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. http://necolas.github.io/normalize.css/
this happens because of default h1 "line height". you can add line-height property with any desired value like this:
h1{
line-height: 1em;
}
如果您使用position: absolute
确保在父元素上指定position: relative
,它应相对于(在您的情况下为<body>
),看看是否有帮助。
You can do:
h1{
margin:0
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.