Search code examples
cssbackground-image

Adding text elements to div with a background-image is causing white space to appear around the image


I have the following CSS:

body{
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

#section-one{
  background-image: url('https://i.picsum.photos/id/738/200/300.jpg?hmac=x-GpfBAQrKyKnrXqne7UJ3rdVnkGD7e-uRhpCcZWb9I'); /*random image*/
  background-repeat:no-repeat;
  background-position: center center;
  background-size: 100%;
  height: 60vh;
}

If I apply that to an empty div as such:

<div id='section-one'>
</div>

The background image would take effect and there would be no white space around it(https://codepen.io/ob98/pen/JjXEMPK). However, when I try to add text to #section-one:

<div id='section-one'>
     <ul>
       <li>Item One</li>
       <li>Item Two</li>
       <li>Item Three</li>
     </ul>
     <div id="tagline">
       <h1>Text</h1>
       <h1>Text</h1>
     </div>
 </div>

White space appears above and to the right of the background image. This can be seen here: https://codepen.io/ob98/pen/MWyJOMd

If anyone knows what is causing this and how to fix it would be greatly appreciated.


Solution

  • You have a margin of 16px wrapping your tags.

    Give the <ul> tag an id then overwrite the default classes by applying the css below.

    body {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    #section-one {
      background-image: url('https://i.picsum.photos/id/738/200/300.jpg?hmac=x-GpfBAQrKyKnrXqne7UJ3rdVnkGD7e-uRhpCcZWb9I');
      /*random image*/
      background-repeat: no-repeat;
      background-position: center center;
      background-size: 100%;
      height: 60vh;
    }
    ul#items {
      margin: 0px;
      }
    <div id='section-one'>
      <ul id='items'>
        <li>Item One</li>
        <li>Item Two</li>
        <li>Item Three</li>
      </ul>
      <div id="tagline">
        <h1>Text</h1>
        <h1>Text</h1>
      </div>
    </div>