Flexbox很多嵌套的孩子

时间:2015-12-20 12:21:01

标签: html css flexbox sticky-footer

我在flexbox上阅读了很多帖子,但仍有一个问题让我烦恼。 我想根据this guide使用flexbox设置一个粘性页脚。

但是,在我的页面内容中,我希望拥有尽可能多的嵌套div,并让它们与父级具有相同的高度。

问题是,在启用flexbox时,在每个子项上设置height: 100%(就像我在非flexbox场景中所做的那样)的工作方式不同。这会导致孩子的身高增加(超过父母)。

为了使这更清楚,这是一个codepen without flexbox

codepen with flexbox

你可以在flexbox场景中看到即使我不想要它,页脚也会获得绿色bakground。

HTML:

<div class="sticky-footer-container">
  <div class="sticky-footer-content">
    <div class="page-container">
      <div class="main-menu">
        <div class="main-menu-selection">
          <div class="main-menu-selection-text">
            <div class="some-other-class">
              Some text
            </div>
          </div>
        </div>
        <div class="main-menu-selection">
          <div class="main-menu-selection-text">
            <div class="some-other-class">
              Some text
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="sticky-footer">
    Some footer content
  </div>
</div>

SCSS:

* {
  box-sizing: border-box;
}

html,
body {
  height: 100%;
  background: silver;
  padding: 0;
  margin: 0;
}

.sticky-footer-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  .sticky-footer-content {
    height: 100%;
    background: blue;
    flex: 1;
    div {
      height: 100%;
    }
    .main-menu-selection {
      height: 50%;
    }
  }
}

.some-other-class {
  background: green;
}

为了解决这个问题,任何嵌套div都必须成为flex-container

换句话说,有没有办法在树的某个点“停止弹性传播”,所以所有的div都获得父高度而没有溢出?

1 个答案:

答案 0 :(得分:0)

display: flexbox 实际上不是有效值:)

您还需要设置高度并最终从html继承:

.sticky-footer-container {
  display: flex;
  flex-direction: column;
}

.sticky-footer-content {
  flex: 1;
}
/* let's inherit some height to pull the footer down */
html,
body,
.sticky-footer-container {
  height: 100%;
  margin: 0;
}

.sticky-footer {
  display: flex;/* flex item can be flexboxes as well */
  background: turquoise;
  align-items: center;
  justify-content: center;
  min-height: 3em;
}
<div class="sticky-footer-container">
  <div class="sticky-footer-content">
    <div class="page-container">
      <div class="main-menu">
        <div class="main-menu-selection">
          <div class="main-menu-selection-text">
            <div class="some-other-class">
              Some text
            </div>
          </div>
        </div>
        <div class="main-menu-selection">
          <div class="main-menu-selection-text">
            <div class="some-other-class">
              Some text
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="sticky-footer">
    Here my footer
  </div>
</div>