【问题标题】:How to vertically/horizontally center a CSS background-image with padding如何使用填充垂直/水平居中 CSS 背景图像
【发布时间】:2019-04-17 20:58:41
【问题描述】:

我让它垂直和水平居中:

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 背景图像,而不是 <img>

【问题讨论】:

    标签: html css background-image


    【解决方案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;
    }

    【讨论】:

      【解决方案2】:

      这是因为 CSS 默认使用 content-box box-sizing 方法。这意味着 width = 内容宽度 + padding + 边框height = 内容高度 + padding + 边框

      您可以切换到border-box box-sizing方法,包括宽度和高度的填充和边框。

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

      希望对你有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-17
        • 2011-01-29
        • 2017-04-22
        • 1970-01-01
        • 1970-01-01
        • 2013-05-18
        • 2011-11-24
        相关资源
        最近更新 更多