我可以把CSS背景定位到“底部减去x像素”吗?

6
我需要将背景图定位在屏幕底部。但是在移动设备的分辨率上,我想将它显示在底部以下100像素,就像“底部减去100像素”。在CSS中是否可以实现这样的效果?

你是在使用背景位置属性来设置背景还是在所有元素后面使用图像标签?需要看一下你的代码。 - salad_bar_breath
你应该将HTML标记与其他CSS依赖项一起添加,否则回答会更多地猜测而非实际解答。 - Clemens Himmer
2个回答

18

是的,使用background-position属性的四值语法可以实现。

表述

// This two-value declaration
background-position: center bottom
// Is equivalent of this four-value declaration
background-position: center 0px bottom 0px

免责声明:支持的浏览器包括Chrome 25+,Firefox 13+,IE9+,Safari 7+

在您的情况下

因此,您可以将背景定位为“底部减100像素”:

background-position: center bottom -100px

示例:

.container {
  height: 190px;
  padding: 1em;
  margin: 0 auto 1em;
  border: 1px solid #333;
  text-align: center;
  
  background-image: url('http://lorempixel.com/200/140/city/4');
  background-repeat: no-repeat;
  background-position: center bottom;
}
.plus {
  background-position: center bottom 20px;
}
.minus {
  background-position: center bottom -20px;
}
<div class="container">
    background-position:<br>
    center bottom
</div>
<div class="container plus">
    background-position:<br>
    center bottom 20px
</div>
<div class="container minus">
    background-position:<br>
    center bottom -20px
</div>

查看MDN 文档


4
你的意思是:背景定位为居中底部,偏移量为-100像素;http://codepen.io/anon/pen/LGyLGN - G-Cyrillus
这取决于你想以哪种方式移动背景。 - tzi
好吧,他要求底部减去100像素... ;) - G-Cyrillus
你说得对。所以我改了。谢谢。我觉得有点混淆了,我们通常是从屏幕顶部参考位置。他可能是指“100vh - 100px”。 - tzi
1
注意:您实际上不能使用 center 0px bottom 0px:您无法定义“距中心100像素”(到哪里?)。它只适用于 topbottomleftright - Cladiuss

2
如果您正在使用background属性,请使用以下代码:
.background{
    background-position: center bottom -100px
}

如果您想定位与背景类似的标签,请尝试使用:
.background{
    margin-bottom -100px;
}

或者

.background{
    bottom: -100px;
    position: absolute;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接