简体   繁体   中英

How to add padding to centered background-image on html element

Right now I am doing this:

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

The image is 3000x1500px let's say. I would like for it to be centered with 100px of padding, and for it to scale down the image so it fits in the center (vertically and horizontally). Right now the padding isn't doing anything and the image is being clipped for being too large I think. I also don't want to use an <img> element, only using background-image in CSS.

You may consider the background on the body element then you set another background on the html to avoid the background propagation and some unwanted effects 1 . Then you can adjust background-size to scale down the background.

Using cover :

 body { height: 100%; background: url(https://picsum.photos/1200/1200?image=0) center/cover no-repeat; box-sizing: border-box; background-origin: content-box; background-clip: content-box; /*don't show on the padding*/ padding: 50px; margin:0; } html { background:#fff; height:100%; } 

Or 100% 100% (centring in this case will be useless)

 body { height: 100%; background: url(https://picsum.photos/1200/1200?image=0) center/100% 100% no-repeat; box-sizing: border-box; background-origin: content-box; /*background-clip: content-box; no more needed*/ padding: 50px; margin:0; } html { background:#fff; height:100%; } 

Also with contain

 body { height: 100%; background: url(https://picsum.photos/1200/1200?image=0) center/contain no-repeat; box-sizing: border-box; background-origin: content-box; /*background-clip: content-box; no more needed*/ padding: 50px; margin:0; } html { background:#fff; height:100%; } 


1 The first code applied directly to html:

 html { height: 100%; background: url(https://picsum.photos/1200/1200?image=0) center/cover no-repeat; box-sizing: border-box; background-origin: content-box; background-clip: content-box; /*this will not work as expected*/ padding: 50px; } 

This updated css can fixed your problem (I am sure this will work for you)

html{
  margin:0px;
  padding:0px;
}
body{
  width: 100vw;
  height: 100vh;
  background: url(https://picsum.photos/1200/1200?image=0) center center no-repeat;
  box-sizing: border-box;
  background-origin: content-box;
  background-clip: content-box;
  background-size:calc(100% - 100px) calc(100% - 100px);
  margin:0px;
}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM