一个flexbox嵌套在另一个flexbox里面?

6
我正在尝试在flexbox内部实现另一个flexbox。虽然第一个(换行)的flexbox可以工作,但内部的那个却没有任何效果。有没有办法让它起作用?
我要做的是有效地拥有两个粘性页脚,并使两者的高度达到页脚的高度。

html, body {
  height: 100%;
  margin: 0; padding: 0;  /* to avoid scrollbars */
}

#wrapper {
  display: flex;  /* use the flex model */
  min-height: 100%;
  flex-direction: column;  /* learn more: http://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ */
}

#header {
  background: yellow;
  height: 100px;  /* can be variable as well */
  
}

#body {
  flex: 1;
  border: 1px solid orange;
  height: 100%:
}
#wrapper2 {
  display: flex;  /* use the flex model */
  min-height: 100%;
  flex-direction: column;
}
#body2 {
  border: 1px solid purple;
  flex: 1;
}
#footer2 {
  background: red;
  flex: 0;
}

#footer{
  background: lime;
}
<div id="wrapper">
  <div id="body">Bodyof<br/>
    variable<br/>
    height<br/>
    <div id="wrapper2">
    <div id="body2">
    blah
    </div>
    <div id="footer2">
    blah<br />
    blah
    </div>    
    </div>
    </div>
  <div id="footer">
    Footer<br/>
    of<br/>
    variable<br/>
    height<br/>
  </div>
</div>

JS Fiddle


我认为你遇到的问题都是HTML相关的,如果你将footer 2移出#wrapper2,它就能正常工作。 - T04435
问题可能出在wrapper2 div上。您将其最小高度设置为100%,但它没有延伸到页脚,这就是为什么第二个页脚不在底部的原因。您可能需要以像素为单位给它最小高度才能使flex起作用。 - Hamza Ishak
将min-height设置为像素会破坏flexbox的目的。我想要的是两个body都向下延伸到底部,但如果窗口高度发生变化,它们也会自动调整大小。 - Shixma
1个回答

6

您已经接近成功了,只需要两个步骤:

  1. #body 设为弹性容器。
  2. 使用 flex: 1 使 .wrapper2 具有完整的高度。

(我还去掉了百分比高度,您不需要它们。)

body {
  margin: 0;
}
#wrapper {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}
#header {
  background: yellow;
  height: 100px;
}
#body {
  flex: 1;
  border: 1px solid orange;
  display: flex;            /* new */
  flex-direction: column;   /* new */
}
#wrapper2 {
  display: flex;
  flex-direction: column;
  flex: 1;                  /* new */
}
#body2 {
  border: 1px solid purple;
  flex: 1;
}
#footer2 {
  background: red;
}
#footer {
  background: lime;
}
<div id="wrapper">
  <div id="body">
    Bodyof
    <br>variable
    <br>height
    <br>
    <div id="wrapper2">
      <div id="body2">blah</div>
      <div id="footer2">
        blah
        <br>blah
      </div>
    </div>
  </div>
  <div id="footer">
    Footer
    <br>of
    <br>variable
    <br>height
    <br>
  </div>
</div>

jsFiddle

在进行上述调整后,您可以通过以下方式将内部(红色)页脚固定在底部:

  • #body2 上使用 flex: 1,这是您已经拥有的,或者
  • #body2 上使用 margin-bottom: auto,或者
  • #footer2 上使用 margin-top: auto,或者
  • 在容器(#wrapper2)上使用 justify-content: space-between

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接