如何使用填充垂直/水平居中CSS背景图像

时间:2019-04-17 12:45:16

标签: html css background-image

我有这个功能可以将其垂直和水平居中放置

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

那行得通,但是现在我正在尝试添加填充。我想在所有面上都设置10px或20px的填充,因此对于移动设备,它具有一些填充。我已经尝试过了:

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

但是右侧和底部位于视口上方,因此发生了滚动并且不再精确居中。我也尝试过使用margin。想知道如何使它工作。我想尽可能使用CSS背景图片,而不是<img>

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

之所以会这样,是因为CSS默认情况下使用content-box box-sizing方法。这意味着 width =内容宽度+填充+边框,而 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 */
}

希望对您有所帮助!