Rebekah Rebekah - 6 months ago 8
HTML Question

Adding a background that has no top on side margin in css

When adding my background image using CSS, I find that there appears to be a

margin
at the top and sides.

I tried adding
padding: 0; margin: 0;
and
left: 0px; top: 0px;
but this has not fixed the problem.

Here is my html



#header {
background: url(logo.png) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
padding: 0;
margin: 0;
background-size: cover;
left: 0px;
top: 0px;
}

<div id="header">
<h1>Hello World!</h1>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>
<p>The background-image is fixed. Try to scroll down the page.</p>

</div>




Answer

body and headings (<h1> to <h6>) has default margin so you need to reset it

body,
h1 {
  margin: 0
}
#header {
  background: url(//placehold.it/1600x900) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
}
<div id="header">
  <h1>Hello World!</h1>
  <p>The background-image is fixed. Try to scroll down the page.</p>
  <p>The background-image is fixed. Try to scroll down the page.</p>
  <p>The background-image is fixed. Try to scroll down the page.</p>
  <p>The background-image is fixed. Try to scroll down the page.</p>

</div>

Comments