5

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

user3203425
  • 2,919
  • 4
  • 29
  • 48

8 Answers8

5

You need to add margin:0;:

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

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

Simply Craig
  • 1,084
  • 1
  • 10
  • 18
5

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.

Community
  • 1
  • 1
skobaljic
  • 9,379
  • 1
  • 25
  • 51
2

Remove top margin on your h1:

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

h1 {
    background-color: lime;
    margin-top: 0;
}
austinthedeveloper
  • 2,401
  • 19
  • 27
2

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.

Brittany
  • 96
  • 1
  • 9
0
<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/

Vnz Dichoso
  • 182
  • 1
  • 2
  • 11
0

this happens because of default h1 "line height". you can add line-height property with any desired value like this:

h1{
    line-height: 1em;
}
peiman
  • 1
  • 1
-1

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.

-1

You can do:

h1{
    margin:0
}
tika
  • 7,135
  • 3
  • 51
  • 82