[Solved] Unwanted top margin for h1 element

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:

enter image description here

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:

enter image description here

why is that happening? I’m using chrome.

Thanks

Solution #1:

You need to add margin:0;:

h1 {
    margin:0;
    background-color: lime;
}

JSFiddle: http://jsfiddle.net/tb39am7s/

Respondent: Simply Craig

Solution #2:

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.

Respondent: skobaljic

Solution #3:

Remove top margin on your h1:

http://jsfiddle.net/austinthedeveloper/wwzxn8gx/

h1 {
    background-color: lime;
    margin-top: 0;
}

Solution #4:

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.

Respondent: Brittany

Solution #5:

<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/

Respondent: Vnz Dichoso

Solution #6:

If you use position: absolute make sure to specify position: relative on the parent element it should be relative to (in your case this would be <body>) and see if this helps.

Respondent: Stefan Schuchlenz

Solution #7:

You can do:

h1{
    margin:0
}
Respondent: tika

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.