Flexbox,如何获得高度始终垂直拉伸100%以填充空间?

时间:2018-03-20 19:17:06

标签: html css flexbox

enter image description here

https://codepen.io/leon-yum/pen/GxWqMe?editors=1100

尝试重新创建我们在其中一个应用中遇到的问题。我们的应用程序中的补充工具栏从不延伸100%以适应内容。在上面的示例中,<div class="content-body">也不适合100%的高度。

标记:

  <body>
    <div id="app">
      <section class="h100 w100">
        <main>
          <header>Header</header>
          <section class="content">
            <div class="sidebar">
              <ul>
                <li>Menu 1</li>
                <li>Menu 2</li>
                <li>Menu 3</li>
                <li>Menu 4</li>
                <li>Menu 5</li>
              </ul>
            </div>
            <div class="content-body">
              <p>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et urna vulputate, venenatis tellus eget, vehicula risus. Suspendisse potenti. Sed fermentum pulvinar diam eu suscipit. Etiam cursus arcu dapibus turpis pulvinar, at lobortis tortor dapibus. Morbi pellentesque fringilla sem at luctus. Sed sagittis leo ut ligula hendrerit, at sollicitudin massa efficitur. Phasellus volutpat nibh ante, nec fermentum ex hendrerit ultricies. Suspendisse tempus fringilla aliquam. Praesent eget varius lorem. Phasellus malesuada, purus nec venenatis feugiat, dui lectus porttitor dolor, sollicitudin semper dui libero quis orci. Sed vitae viverra ante, in rutrum massa. Aliquam mollis vel dui eu porta. In ac accumsan augue. Integer placerat egestas dui, quis aliquam libero bibendum non. Pellentesque scelerisque euismod dolor, ac gravida est mattis non. Suspendisse potenti.
              </p>
            </div>
          </section>
        </main>
      </section>
    </div>
  </body>

CSS

body {
  margin: 0;
  font-family: Arial;
  color: white;
}

.w100 { width: 100%; }
.h100 { width: 100%; }

header {
  padding: 20px;
/*   width: 100%; */
  height: 20px;
  color: brown;
  background: cyan;
}

#app {
  width: 100%;
  height: 100%;
  background: #212121;
}

.content {
  display: flex;
  flex: 1 1 auto;
  height: 100%;
}

.content-body {
  flex: 1 1 auto;
  padding: 20px;
  background: #333;
}

.sidebar {
  background: #666;
}

2 个答案:

答案 0 :(得分:1)

我通过增加高度来修复它:100vh;几个东西(html,body,h100 class和&#34; main&#34;元素.100vh优于100%因为它意味着100%的浏览器垂直高度(100%高度可能会改变,取决于一些变量,如父容器)。

html {
  height: 100vh;
  overflow: hidden;
}

body {
  margin: 0;
  padding: 0;
  font-family: Arial;
  color: white;
  height: 100vh;

}

.w100 { width: 100%; }
.h100 { height: 100vh; }

header {
  padding: 20px;
/*   width: 100%; */
  height: 20px;
  color: brown;
  background: cyan;
}

#app {
  width: 100%;
  height: 100%;
  background: #212121;
}

...

请在此处查看我的codepen:https://codepen.io/anon/pen/oqZLJQ?editors=1100

答案 1 :(得分:0)

身高:100vh; 使用上面的css元素根据屏幕高度自动调整高度。