HTML背景图像偏离中心x像素

rho*_*ron 55 html css

我想将图像作为网页的背景,但是它相对于中心偏移了一些像素.

我怎样才能做到这一点?

我想要:

background-image: url("bg.png");
background-position: 25% center;
background-attachment: fixed;
background-repeat: no-repeat;
Run Code Online (Sandbox Code Playgroud)

但不是25%,我想要的东西是"中心 - 50px".这有什么解决方案吗?

Luk*_*uke 68

我相信我有一个能够达到你想要的解决方案:

背景图像(特别是页面背景)相对于中心偏移了多个像素.

这仅使用HTML和CSS - 不需要JavaScript.


更新

现在可以使用background-positioncalc作为CSS单元轻松实现.

以下CSS将获得与先前解决方案相同的结果(请参阅下面的"原始解决方案"):

#background-container {
    width: 100%;

    background-image: url("background-image.png");
    background-position: calc(50% - 50px) 50%;
    background-repeat: no-repeat;
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您需要支持旧版IE,不要使用此方法.


原始方案

#background-container {
    width: 100%;
    left: -100px; /* this must be TWICE the required offset distance*/
    padding-right: 100px; /* must be the same amount as above */

    background-image: url("background-image.png");
    background-position: center;
    background-repeat: no-repeat;
}
Run Code Online (Sandbox Code Playgroud)

这样做是将整个容器水平移动指定的量(在这种情况下向左移动100px).因为背景图像相对于容器居中,所以它与容器一起向左移动.

填充修复了由于移动而出现在容器右侧的100px空白空间.背景图像通过填充显示.因为浏览器使用边框值而不是默认的内容框值来计算背景大小和位置,所以背景图像有效地移回到右边50px - 填充距离的一半.(感谢ErikE的澄清).

因此,您的偏移/填充必须是所需偏移距离的两倍.

我在这里为您准备了一个示例页面:http: //www.indieweb.co.nz/testing/background-offset-center.html

玩一个调整窗口大小的游戏.您将看到紫色和蓝色背景图像(放置在标记页面中心的较深背景图像上)保持在页面中心左侧的50px(偏移/填充距离的一半).



小智 47

使用background-position: center;与...相同background-position: 50% 50%;.

因此,您可以使用calcCSS中的一些简单数学作为任何长度值的替代,例如:

background-position: calc(50% - 50px) 50%;
Run Code Online (Sandbox Code Playgroud)

将中心背景图像,但将其向左移50像素.

  • 很好的答案.现在2016年对于"calc()"有很好的支持:http://d.pr/i/GrAk (3认同)

Dus*_*ine 6

因此,您希望它向左移动50像素居中.除非您处理绝对尺寸,否则我会以透明空间的形式将50像素添加到图像中.