html - 在 CSS 中为背景图像添加边距

标签 html css background background-image

我正在尝试向背景图像添加固定边距,但遇到了麻烦。我希望图像占据屏幕宽度的大约 70%,位于屏幕的右中心,然后在顶部、底部和右侧具有相等的边距。

这是我目前的背景图像代码:

html, body {

width: 100%;
height: 100%;
margin: 0 auto;
font-family: 'Roboto Condensed', sans-serif;
background: url(http://japesfawcett.com/img/bg.jpg) no-repeat right center fixed; 
background-size: 70% auto;

}

我已将完整的当前代码放入笔中,here .

下面的图片也有助于说明我想要实现的目标:

Image

最佳答案

您还需要考虑调整背景位置

以下示例的顶部/右侧/底部为 30px,图像占据宽度的 70%:

html {
  height: 100%;
  background: linear-gradient(to right,white 30%,red 0);
}

body {
  height: 100%;
  margin: 0 auto;
  background-image: url(https://i.picsum.photos/id/107/800/800.jpg);
  background-size: calc(70% - 30px) calc(100% - 60px);
  background-position: right 30px top 30px;
  background-repeat: no-repeat;
}

您还可以考虑background-clip宽度填充或边框:

html {
  height: 100%;
  background: linear-gradient(to right,white 30%,red 0);
}

body {
  height: 100%;
  padding:30px 30px 30px 0;
  box-sizing:border-box;
  margin: 0 auto;
  background-image: url(https://i.picsum.photos/id/107/800/800.jpg);
  background-size: 70% 100%;
  background-position: right;
  background-clip:content-box;
  background-repeat: no-repeat;
}

关于html - 在 CSS 中为背景图像添加边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48660372/

相关文章:

html - 如何在css中播放动画后更改按钮颜色

html - 你能在 CSS 中指定一个虚拟顶部吗?

ios - 当应用程序在后台iOS中时发出声音

html - 背景剪辑与背景大小的封面喙封面?

html - 如何使多个左列固定并滚动 HTML 表格中的其余列?

javascript - AngularJS:ng-model 没有在 UI 中更新

css - 重叠侧边栏列表 CSS

html - 在 css 中使用背景图像以及页面中心的白色背景

python - 用于选择 div 之前的所有同级的 XPath

javascript - 如何在鼠标悬停在照片下方添加说明? (照片库)