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

问题描述 投票:0回答:2

我有这个垂直和水平居中:

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

但右侧和底部越过视口,因此滚动发生并且它不再完全居中。我也试过使用保证金。想知道如何让这个工作。我想尽可能使用CSS background-image而不是<img>

html css background-image
2个回答
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;
}

0
投票

这是因为CSS默认使用内容框大小调整方法。这意味着width =内容宽度+填充+边框和高度=内容高度+填充+边框。

您可以切换到边框框大小调整方法,其中包括宽度和高度的填充和边框。

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 */
}

我希望能帮到你!

© www.soinside.com 2019 - 2024. All rights reserved.