知道一个好的CSS技术的全屏背景图像?

时间:2013-03-24 23:23:24

标签: html css image css3 background-image

我在网上浏览并尝试了各种方法来解决这个问题,但还没有找到一种适合我的技术。我希望我的网站的背景图像居中,填满整个浏览器屏幕,并使用响应式设计。

除了CSS3 / background-size:cover之外还有一个简单的技巧吗?这对我来说根本不起作用(不知道为什么......)。

4 个答案:

答案 0 :(得分:3)

<强> LIVE DEMO

body{
  background:url(img.jpg) center center fixed;
  background-size:cover; // CSS3 *
}

注意: CSS3 。对于其他浏览器,请尽量使其变得丑陋! ;)

答案 1 :(得分:2)

除了CSS之外,如果您不反对涉及HTML的解决方案,则可以使用background-size: cover标记模拟img行为。

HTML:

<body>
    <div id="image-matte">
        <img src="..."/>
    </div>

    ... Page content below ...

</body>

CSS:

#image-matte {
    position: fixed;
    top: 0%;
    left: -50%;
    width: 200%;
    height: 200%;
}

#image-matte img {
    display: block;
    margin: auto;
    min-height: 50%;
    min-width: 50%;
}

/* Covers the image to prevent pointer interaction */
#image-matte:after {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

编辑:要获得垂直和水平居中的背景图像,您需要在包装器div和保存图像本身的内部div之间创建表/表格单元关系。 .. HTML和CSS看起来像这样:

HTML:

<div id="image-matte">
    <div>
        <img src="..."/>
    </div>
</div>

CSS:

#image-matte {
    position: fixed;
    display: table;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    text-align: center;
}
#image-matte div {
    vertical-align: middle;
    display: table-cell;
}
#image-matte img {
    position: relative;
    text-align: center;
    min-height: 50%;
    min-width: 50%;
}

/* Covers the image to prevent pointer interaction */
#image-matte:after {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

工作示例:http://jsfiddle.net/qkpvb/

答案 2 :(得分:0)

要在所有浏览器上运行良好,我建议使用jQuery解决方案:

HTML

<img src='./templates/lights3.jpg' alt="bg" id="bg"/>

CSS

#bg { 
    position: fixed; 
    top: 0; 
    left: 0;
    z-index: -5000; // Yes I always overdo ^^ (that's not very clean)
}

.bgwidth { 
    width: 100%;
}

.bgheight { 
    height: 100%;
}

JQUERY

$(window).load(function() {    
var theWindow        = $(window),
    $bg              = $("#bg"),
    aspectRatio      = $bg.width() / $bg.height();              
function resizeBg() {
    if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
        $bg
            .removeClass()
            .addClass('bgheight');
    } else {
        $bg
            .removeClass()
            .addClass('bgwidth');
    }           
}                           
theWindow.resize(resizeBg).trigger("resize");
});

此解决方案将响应并相对于浏览器窗口的大小调整背景图像的大小。

答案 3 :(得分:0)

尝试在链接中的tag或css中添加此html标记:

<img src="img/beach.jpg" 

style="width:100%;height:100%;position:absolute;top:0;left:0;z-index:-5000;">

http://thewebthought.blogspot.com/2010/10/css-making-background-image-fit-any.htmlg

相关问题