繁体   English   中英

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

[英]How to vertically/horizontally center a CSS background-image with padding

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

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 background-image代替<img>

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

发生这种情况是因为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 */
}

希望对您有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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