Lance Pollard
Lance Pollard

Reputation: 79268

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>.

Upvotes: 0

Views: 744

Answers (2)

This happens because CSS uses, by default, the content-box box-sizing method. It means that width = content width + padding + border and height = content height + padding + border.

You can switch to the border-box box-sizing method, that includes padding and border in width and height.

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

  box-sizing: border-box; /* switches to border-box method */
}

I hope that helps you!

Upvotes: 0

Paulie_D
Paulie_D

Reputation: 115047

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;
}

Upvotes: 1

Related Questions