首页 > 解决方案 > 如何在 html 元素上为居中的背景图像添加填充

问题描述

现在我正在这样做:

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

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

标签: htmlcssbackgroundbackground-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;
}


推荐阅读