html - 如何在 html 元素上为居中的背景图像添加填充
问题描述
现在我正在这样做:
html {
width: 100%;
height: 100%;
background: url(/icon.png) center center no-repeat;
box-sizing: border-box;
background-origin: content-box;
padding: 100px;
}
假设图像是3000x1500px。我希望它以 100px 的填充为中心,并缩小图像以使其适合中心(垂直和水平)。现在填充没有做任何事情,并且我认为图像因太大而被剪裁。我也不想使用<img>
元素,只background-image
在 CSS 中使用。
解决方案
您可以考虑 body 元素的背景,然后在 html 上设置另一个背景,以避免背景传播和一些不需要的影响1。然后您可以调整background-size
以缩小背景。
使用cover
:
body {
height: 100%;
background: url(https://picsum.photos/1200/1200?image=0) center/cover no-repeat;
box-sizing: border-box;
background-origin: content-box;
background-clip: content-box; /*don't show on the padding*/
padding: 50px;
margin:0;
}
html {
background:#fff;
height:100%;
}
或100% 100%
(在这种情况下居中将无用)
body {
height: 100%;
background: url(https://picsum.photos/1200/1200?image=0) center/100% 100% no-repeat;
box-sizing: border-box;
background-origin: content-box;
/*background-clip: content-box; no more needed*/
padding: 50px;
margin:0;
}
html {
background:#fff;
height:100%;
}
还与contain
body {
height: 100%;
background: url(https://picsum.photos/1200/1200?image=0) center/contain no-repeat;
box-sizing: border-box;
background-origin: content-box;
/*background-clip: content-box; no more needed*/
padding: 50px;
margin:0;
}
html {
background:#fff;
height:100%;
}
1直接应用于html的第一个代码:
html {
height: 100%;
background: url(https://picsum.photos/1200/1200?image=0) center/cover no-repeat;
box-sizing: border-box;
background-origin: content-box;
background-clip: content-box; /*this will not work as expected*/
padding: 50px;
}
推荐阅读
- angular - 无法点击下拉菜单的外侧 - selenium angular
- c# - 设定值
有条件的? - integration - XRAY 和 WebdriverIO 集成
- amazon-web-services - AWS RDS 作为 AWS Managed Grafana 中的数据源
- c# - 从 API 下载 JSON 文件并将其保存在文件中
- html - 为 Outlook 创建电子邮件签名
- keras - TypeError:“Sub”Op 的输入“y”的类型为 float32,与参数“x”的类型 int64 不匹配
- python - 用于输入模型的 Django 自定义 SQL
- python-3.x - 使用正则表达式从文本中删除某些模式
- mysql - 在 Percona Mysql 中将审计日志更改为 JSON 格式