CSS中的全屏响应式背景图像

4
我希望将这张图片作为我的网页背景图片。然而,问题是该图片未覆盖整个页面,如您在此预览中所见,并在最右侧重复出现。是否有一种方法可以使图像覆盖整个页面(无论是拉伸、重新调整大小还是其他新方法)。

我的代码:

<!DOCTYPE HTML>
<html>

    <head>
        <title>Angry Birds Star Wars</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <style>
            body {
                background: url('http://www.androidtapp.com/wp-content/uploads/2012/11/Angry-Birds-Star-Wars-Menu.png');
            }
        </style>
    </head>

    <body></body>

</html>

谢谢。

更新:

我现在终于相信几乎没有什么可以让那个图像完全适合我的电脑屏幕。现在我没事了,并且正在向前发展,请现在不要发布答案。

5个回答

12

jsBin演示

background: url(image.jpg) fixed 50%;
background-size: cover;                 /* PS: Use separately here cause of Safari bug */

上述内容仅是fixed(背景附着)的一种简写形式。


上述内容只是一种简写形式:

background-image      : url(image.jpg);
background-attachment : fixed;
background-position   : 50% 50%;     /* or: center center */
background-size       : cover;       /* CSS3 */

在所有现代浏览器中,你可以使用以下代码,但 Safari 除外

background: url(image.jpg) fixed 50% / cover;

在背景样式中,/ 用于分隔并区分 positionsize(因为 position 可以接受单个或多个 (X,Y) 值),但 Safari 存在这种 / 简写的 Bug,所以请按上述描述使用。


@GaurangTandon这个答案和我的早期答案有什么不同? - cbr
@RokoC.Buljan 所以基本上你的版本不支持旧版浏览器。没错。 - cbr
1
@jCuber ? 旧版浏览器根本就不支持 background-cover,请您解释一下您的陈述。 - Roko C. Buljan
@RokoC.Buljan 对不起,我使用的是过时的信息。 - cbr

2

使用 background-size 属性,并将背景重复设置为 no-repeat

像这样:

body { 
        background: url('http://www.androidtapp.com/wp-content/uploads/2012/11/Angry-Birds-Star-Wars-Menu.png') no-repeat center center fixed;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

See this jsFiddle


好的,现在情况稍微好了一些,但是图片底部和顶部被切掉了一点(请对比原始图片和处理后的图片)。 - Gaurang Tandon
@GaurangTandon 这是因为使用了 center center 定位方式。如果你想让背景图片锚定在左上角,只需将其更改为 top left 即可。 - cbr
那样做甚至更好,center center 更好。 - Gaurang Tandon

1
将此设置为您的背景图像。
background-size: cover

你不能这样使用它,需要将它们分别作为属性,如background-image和background-size。 - slash197

0
background-size: 100% 100%;
background-position: top left;
background-repeat: no-repeat;

应该可以解决问题。请注意 - 您可以将位置和重复组合到初始背景属性中

并应用

html, body { min-height: 100%; min-width: 100%; }

-1

您可以始终使用绝对定位的div来设置100%的宽度和高度,并使用z-index使其成为背景,然后您可以使用相同的css插入图像。 谢谢


-5 不不不,如果你尝试了你所说的,图像将会随着窗口的调整而拉伸。那是不好的。希望你不喜欢扭曲的图像... :) 至于 z-index,在这种情况下绝对没有必要设置 z-index。 - Roko C. Buljan

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