在下面的HTML中,我手动将中间div的高度设置为200px。如何自动调整此高度,以使div的高度等于浏览器中可见区域的高度?这可以用纯CSS完成,还是需要JavaScript?
<p>Scroll Up and Down this page to see the parallax scrolling effect.</p>
<div class="parallax"></div>
<div class="red">
Scroll Up and Down this page to see the parallax scrolling effect.
This div is just here to enable scrolling.
Tip: Try to remove the background-attachment property to remove the scrolling effect.
</div>
CSS:
.parallax {
/* The image used */
background-image: url("http://az-themes.bluxart.netdna-cdn.com/ibuki/wp-content/uploads/2014/06/blog-img.jpg");
/* Set a specific height */
height: 200px;
/* Create the parallax scrolling effect */
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.red {
height:1000px;
background-color:red;
color:white;
font-size: 40px;
}
可以找到Wokring示例here。
答案 0 :(得分:4)
使用vh
单位 - 因此200px变为100vh以填充屏幕的整个高度。
但请确保在内容超出视口显示的时间内加入min-height
。
关于这个的兼容性:
http://caniuse.com/#feat=viewport-units
Firefox:自Firefox 19(2013)以来支持
Chrome:支持部分自Chrome 20(2012)以来,Chrome 26(2013)以来的全面支持
Safari:部分自Safari 6(2012)起支持,自Safari 6.1(2013)以来的全面支持
IE:IE 9(2011)以来的部分支持
Edge:自Edge 12(2015)以来的部分支持
当我说部分支持时,在所有这些情况下,他们都不支持vmax
,但您无论如何都不会使用{。}}。
.parallax {
/* The image used */
background-image: url("http://az-themes.bluxart.netdna-cdn.com/ibuki/wp-content/uploads/2014/06/blog-img.jpg");
/* Set a specific height */
height: 100vh;
/* Create the parallax scrolling effect */
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.red {
height: 1000px;
background-color: red;
color: white;
font-size: 40px;
}
&#13;
<p>Scroll Up and Down this page to see the parallax scrolling effect.</p>
<div class="parallax"></div>
<div class="red">
Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling. Tip: Try to remove the background-attachment property to remove the scrolling effect.
</div>
&#13;
您也可以使用jQuery执行此操作,使用.height()
来获取窗口高度。
$(document).ready(function() {
wh = $(window).height();
$(".parallax").css({
"height": wh
});
});
&#13;
.parallax {
/* The image used */
background-image: url("http://az-themes.bluxart.netdna-cdn.com/ibuki/wp-content/uploads/2014/06/blog-img.jpg");
/* Set a specific height */
height: 100vh;
/* Create the parallax scrolling effect */
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.red {
height: 1000px;
background-color: red;
color: white;
font-size: 40px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll Up and Down this page to see the parallax scrolling effect.</p>
<div class="parallax"></div>
<div class="red">
Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling. Tip: Try to remove the background-attachment property to remove the scrolling effect.
</div>
&#13;