额外的 div 导致图像高度无法正确缩放(显示:flex)



我从这里拿走了代码。代码运行良好,但是当我添加额外的div以用类fullwidth包装div时,图像高度不会根据屏幕高度均匀缩放。

这是它最初的样子:

body,
html {
height: 100%;
}
.fullwidth {
display: flex;
flex-direction: column;
height: 100%;
}
.repeat-x {
flex: 1;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
}
.bg-1 {
background-image: url(http://oi65.tinypic.com/28v4p6u.jpg);
}
.bg-2 {
background-image: url(http://oi65.tinypic.com/28v4p6u.jpg);
}
.bg-3 {
background-image: url(http://oi65.tinypic.com/28v4p6u.jpg);
}
<div class="fullwidth">
<div class="repeat-x bg-1">&nbsp;</div>
<div class="repeat-x bg-2">&nbsp;</div>
<div class="repeat-x bg-3">&nbsp;</div>
</div>

用另一div包裹fullwidth后:-

body,
html {
height: 100%;
}
.fullwidth {
display: flex;
flex-direction: column;
height: 100%;
}
.repeat-x {
flex: 1;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
}
.bg-1 {
background-image: url(http://oi65.tinypic.com/28v4p6u.jpg);
}
.bg-2 {
background-image: url(http://oi65.tinypic.com/28v4p6u.jpg);
}
.bg-3 {
background-image: url(http://oi65.tinypic.com/28v4p6u.jpg);
}
<div id="newid">
<div class="fullwidth">
<div class="repeat-x bg-1">&nbsp;</div>
<div class="repeat-x bg-2">&nbsp;</div>
<div class="repeat-x bg-3">&nbsp;</div>
</div>
</div>

您可以选择以下选项之一,将#newid放大到当前视口的整个高度:

#newid {
height: 100vh; /* this is how you do it in 2017 */
height: 100%;
}

供参考:如果您想更深入地了解 css 单元,我可以强烈推荐这篇文章:CSS 单位 - vh/vw 和 % 有什么区别?

height: 100%添加到newid容器 - 这允许flexbox继承文档的height

请参阅下面的演示:

body,
html {
height: 100%;
}
#newid {
height: 100%;
}
.fullwidth {
display: flex;
flex-direction: column;
height: 100%;
}
.repeat-x {
flex: 1;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
}
.bg-1 {
background-image: url(http://oi65.tinypic.com/28v4p6u.jpg);
}
.bg-2 {
background-image: url(http://oi65.tinypic.com/28v4p6u.jpg);
}
.bg-3 {
background-image: url(http://oi65.tinypic.com/28v4p6u.jpg);
}
<div id="newid">
<div class="fullwidth">
<div class="repeat-x bg-1">&nbsp;</div>
<div class="repeat-x bg-2">&nbsp;</div>
<div class="repeat-x bg-3">&nbsp;</div>
</div>
</div>

把它添加到你的css中:

#newid {
height: 100%;
}

最新更新