How to make a header touch top of page?

Viewed 2429

Trying to make a header touch the top of my page, however there seems to be an automatic margin, even if specified otherwise.

I've tried specifying margin-top: 0, and have set margin: 0 to the body as well.

h1 {
  margin-top: 0px;
}

body {
  margin: 0px;
}
  <h1>test</h1>

Instead of touching the top of the page, the "test" header has an automatic margin at its top.

4 Answers

adding line-height: 75%; seems to do the trick:

h1 {
  margin-top: 0px;
  line-height: 75%;
}

body {
  margin: 0px;
}

Just add the line-height for your h1 tag. Optionally set the line-height for body also.

h1 {
  margin-top: 0px;
  line-height: 18px;
}

body {
  margin: 0px;
  line-height: 1.15;
}
<!DOCTYPE html>
<html>
  <head>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <h1>test</h1>
  </body>
</html>

The header in not touching the top even after setting margins to zero, must be due to line-height.Try to set a colored border i.e. border: 1px solid green. If you see that the border is touching the top then the real reason is the space around text/font due to line-height.

The line-height is set by the standard css rules included in the html page to create proper spacing between text OR by default it is set to normal which uses a standard value. So if you reduce space around text using line-height property it will do the trick but i do not recommend to reduce it less than 1 : line-height: 1

Use Uppercase letters and you will see that your element is already touching the top of the screen so it's logical that the lowercase ones will be sligthly lower.

h1 {
  margin-top: 0px;
}

body {
  margin: 0px;
}
<h1>ÂtestË</h1>

Related