0

I want to add a background image to my web page. The image that I want to use has around 20% transparent padding on all four sides. What attribute should I use so that the background image has an edge-to-edge fit (avoiding the transparent part)?

body{
    background-image: url("bg.png");
    background-size: 90%;
    background-repeat: no-repeat;
}

2 Answers2

1

You can change background image size, and fix them to center:

body{
    background-image: url( "bg.png" );
    background-size: 60% 60%; /* 100% - 40% (top/left + bottom/right paddings) */
    background-position: center;
    background-repeat: no-repeat;
}
0

For something like this, I prefer to add a container element to the page and avoid using body for background images when I need to exercise finite control over display and positioning. This would be my solution:

JSFiddle

Markup

<body>
  <div class="container">
    <div class="media"></div>
  </div>
</body>

SCSS

body {
  padding: 0;
  margin: 0;
}
.container {
  position: absolute;
  width: 100%;
  height: 100%;
  .media {
    width: 100%;
    height: 100%;
    transform: scale(1.4);
    background: {
      image: url("https://i.ytimg.com/vi/cYNlJYQI3Uw/maxresdefault.jpg");
      position: center center;
      size: cover;
      repeat: no-repeat;
    }
  }
}

Notice that I use a CSS reset to remove automatic margin/padding on the body element, and that I allow body to fill the entire viewport.

The container class fills the body element with width and height set to 100%. I use the CSS background-size property to cover the container, then I use the transform property to scale container.

There are many ways to achieve this effect. Alternately, using a background-image property on the body tag will allow me to use background-size to scale the image to obfuscate the image's transparent padding as you described, but it is more difficult to center the image within the container.

Miaplacidus
  • 525
  • 3
  • 7