如何向 html 元素的居中背景图像添加填充

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

现在我正在这样做:

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

假设图像为 3000x1500 像素。我希望它以 100px 的填充居中,并缩小图像以使其适合中心(垂直和水平)。现在填充没有做任何事情,我认为图像因太大而被裁剪。我也不想使用 <img> 元素,只在 CSS.

中使用 background-image

您可以考虑 body 元素的背景,然后在 html 上设置另一个背景以避免背景传播和一些不需要的效果1。然后你可以调整background-size缩小背景。

使用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%;
}

100% 100%(在这种情况下居中将无用)

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

还有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第一个代码直接应用于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;
}

这个更新的 css 可以解决您的问题(我相信这对您有用)

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