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

时间:2017-08-15 07:08:04

标签: html css image css3 flexbox

我从here获取了代码。代码运行良好但是当我添加一个额外的div来封装divfullwidth时,图像高度不会根据屏幕的高度进行相同的缩放。

这就是它最初的样子:

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>

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 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>

3 个答案:

答案 0 :(得分:6)

您可以选择其中一个将#newid放大到当前视口的整个高度:

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

供参考:如果您想深入了解css单位,我强烈推荐这篇文章:CSS Units - What is the difference between vh/vw and %?

答案 1 :(得分:5)

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

见下面的演示:

&#13;
&#13;
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);
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:4)

将此添加到您的css:

#newid {
  height: 100%;
}