知道全屏背景图像的良好 CSS 技术吗?

问题描述 投票:0回答:4

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

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

html image css background-image
4个回答
3
投票

现场演示

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

注意:CSS3。对于其他old浏览器,请使其尽可能丑陋! ;)


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/


0
投票

尝试将此 html 标签添加到链接中的标签或 css 中:

<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


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");
});

此解决方案将具有响应能力,并根据浏览器窗口的大小调整背景图像的大小。

© www.soinside.com 2019 - 2024. All rights reserved.