Search code examples
htmlcssbackground-image

How to vertically/horizontally center a CSS background-image with padding


I have this to center it vertically and horizontally:

html {
  width: 100%;
  height: 100%;
  background: url(/icon.png) center center no-repeat;
}

That works, but now I am trying to add padding. I would like to have 10px or 20px padding on all sides, so for mobile it has some padding. I've tried this:

html {
  width: 100%;
  height: 100%;
  background: url(/icon.png) center center no-repeat;
  background-origin: content-box;
  padding: 20px;
}

But the right and bottom go over the viewport, so scrolling occurs and it's not centered exactly anymore. I've also tried using margin. Wondering how to get this to work. I would like to use CSS background-image if possible, instead of <img>.


Solution

  • Add box-sizing:border-box;

    html {
      width: 100%;
      height: 100%;
      background: url(http://www.fillmurray.com/460/300) center center no-repeat;
      background-origin: content-box;
      padding: 20px;
      box-sizing:border-box;
    }