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

Eel*_*lyn 9 html css image css3 flexbox

我从这里拿了代码.代码运行良好但是当我添加一个额外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);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Ger*_*ann 6

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

#newid {
  height: 100vh; /* this is how you do it in 2017 */
  height: 100%;
}
Run Code Online (Sandbox Code Playgroud)

供参考:如果你想深入研究css单位,我强烈推荐这篇文章:CSS单位 - vh/vw和%之间有什么区别?


kuk*_*kuz 5

添加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);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)