我有一个基本的页面,它有一个标题和一个内容,比方说,里面有一个寄存器:
<div>
<nav>
// header
</nav>
<div class="container-index">
// form
<div>
</div>
现在,问题是我希望表单周围的div 具有与页面底部对齐的背景图像,所以我使用 CSS,如下所示:
html,
body {
height: 100%;
}
.container-index {
background: url('../images/example.jpg') #e74a39;
background-repeat: no-repeat;
background-position: center 100%;
display: flex;
flex-flow: column;
flex-grow: 1;
}
.contaier-index.full-height {
height: 100vh;
}
但是当视口小于内容时,这不起作用,而是背景图像在表单的中途结束,所以我做了这个:
$(window).on('resize scroll', function(e){
var docH = parseInt($(document).height()),
viewPortH = parseInt($(window).height());
if (docH > viewPortH) {
$('.container-index').removeClass('full-height');
} else {
$('.container-index').addClass('full-height');
}
});
$(window).trigger('resize');
这是一种相当糟糕的方式。
有没有办法在 CSS 中做到这一点?
您可以尝试各种可用的属性背景大小:https://www.w3schools.com/cssref/css3_pr_background-size.asp。大多数情况下,背景尺寸:封面应该可以解决您的问题。
我只是用很少的 CSS 更改更新您的代码并删除 jQuery 脚本。试试这个,希望它能帮助你。谢谢
html,
body {
margin: 0;
min-height: 100%;
}
body {
background: url('https://images.unsplash.com/photo-1476820865390-c52aeebb9891?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80') #e74a39;
background-repeat: no-repeat;
background-position: center 100%;
background-size: cover;
}
.container-index {
display: flex;
flex-flow: column;
flex-grow: 1;
height: calc(100vh - 18px);
}
<div>
<nav>
// header
</nav>
<div class="container-index">
// form
<div>
</div>
最后我没有找到合理的 CSS 答案,因此唯一的解决方案是为此保留 JS。