如何 vertically/horizontally 使用填充使 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;
}
但是右侧和底部越过视口,因此发生滚动并且不再完全居中。我也尝试过使用保证金。想知道如何让它工作。如果可能,我想使用 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 = content width + padding + border and height = content height + padding + border.
您可以切换到 border-box box-sizing 方法,该方法包括 padding 和 border 的宽度和高度。
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 */
}
希望对你有帮助!
我用它来垂直和水平居中:
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>
.
添加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 = content width + padding + border and height = content height + padding + border.
您可以切换到 border-box box-sizing 方法,该方法包括 padding 和 border 的宽度和高度。
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 */
}
希望对你有帮助!