如何使用可缩放的全尺寸背景图像制作3个div

时间:2014-01-29 08:12:44

标签: css image html background

我想制作单页网站,因此您必须向下滚动才能查看内容。我有3个不同的内容div。每个div应该有一个不同的背景图像,它应该根据浏览器的大小进行缩放,同时保持图像的纵横比。 希望它有点清楚我想做什么?

这是我目前的css:

.div1 {
height: 927px;
width: 100%;
background-image: url(bg3.jpg);
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
}
.div2 {
height: 927px;
width: 100%;
background-image: url(bg1.jpg);
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
}
.div3 {
height: 927px;
width: 100%;
background-image: url(bg2.jpg);
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
}
body {
    margin-left: 0px;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 0px;
}

这是html:

<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>

</body>

正如您所看到的,它不会将每个div背景图像缩放到正确的浏览器大小。任何人都有一个很好的解决方案吗?

2 个答案:

答案 0 :(得分:0)

我最近这样做了。我必须根据屏幕尺寸为每个div添加5个背景。

别担心让我们试试吧..

你需要js / jquery来获得结果或者我采用jquery来设置div高度精确到屏幕高度..

代码: HTML

 <div class="wrapper">
  <div class="page one"></div>
  <div class="page two"></div>
  <div class="page three"></div>
</div>

<强> CSS

.page{ height: 927px;
       width: 100%;
       -webkit-background-size: 100% 100%;
       -moz-background-size: 100% 100%;
       -o-background-size: 100% 100%;
       background-size: 100% 100%;
       background-repeat: no-repeat;
       background-position: center center; 
      }
.page.one {background-image: url(bg1.jpg);}
.page.two {background-image: url(bg2.jpg);}
.page.three {background-image: url(bg3.jpg);}

<强> jquery的

$(document).ready(function(){
    $('.page').css('height',window.innerHeight)
})

编辑部分: 把它放在你的标题和寒意中:))

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){
    $('.page').css('height',window.innerHeight)
})
</script>
</head>

希望这可以帮助你..

答案 1 :(得分:0)

你的CSS看起来很适合尝试。当用户浏览页面时,div的背景可能会继续滚动。背景表现得像位置:固定;元件。要阻止它,只需添加:

background-attachment: scroll;
background-clip: border-box;

我对包含背景图像的div的静态高度感到困惑。我只是想根据浏览器窗口调整宽度。

有点hacky,但你可以尝试这样做:

html, body
{
    height: 100%;
}

.div1,.div2,.div3
{
    height: 100%;
    width: 100%
    position: absolute;
}

.div1
{
    top: 0;
    background-color: blue;
}

.div2
{
    top: 100%;
    background-color: red;
}

.div3
{
    top: 200%;
    background-color: yellow;
}

请参见此处示例:http://fiddle.jshell.net/bah93/