我正在尝试创建一个布局,顶部带有标题,在其下方是侧边栏和主要内容。

我想让边栏和内容 View 占据标题剩余的垂直空间。问题在于报头可以动态调整大小,因此我无法执行calc()。我的解决方案是使用flexbox方案。

我将视口(viewport)水平分为两部分。一个是标题,一个是侧边栏和主要内容的包装。

边栏向左 float 并给出宽度的百分比,内容向右 float 并给出其余部分。

问题是我试图使侧边栏始终是包装器的100%高度。

我尝试了height: 100%min-height: 100%,但它们不起作用。

我不希望将其绝对定位,因为如果包装器溢出了主要内容,则侧栏将不会相应地扩展。

这是我的笔:http://codepen.io/markt5000/pen/JXNXpW

如您所见,橙色是标题,红色空间是带有侧边栏和内容的包装。

这是布局

<div class="header">
</div>

<div class="row">

  <div id="sidebar">
  </div>

 <div id="main-content">
 </div>

</div>

最佳答案

不需要:

flex 元素上的

  • heightmin-heightcalc
  • 绝对定位
  • float (实际上,它们没有用,因为floats are ignored in a flex formatting context)

  • Flex属性具有使布局起作用所需的全部功能。关键是使用flex: 1使元素扩展容器的整个可用长度。

    因此,标题的高度可以是动态的,并且可以使边栏和主要内容消耗掉剩下的任何高度。没有滚动条。

    这是经过一些修改的代码:

    html { height: 100%; }
    
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    .outer-flex-container {
      height: 100%;
      display: flex;
      flex-direction: column;  /* main flex container stacks items vertically */
    }
    
    .header {
      height: 80px;            /* demo purposes; from your original code */
      background-color: orange;
    }
    
    .nested-flex-container {
      display: flex;           /* inner flex container stacks items horizontally */
      flex: 1;                 /* KEY RULE: tells this second flex item of main container
                                      to consume all available height */
      align-items: stretch;    /* KEY RULE: default setting. No need to include. Tells
                                      children to stretch the full length of the container
                                      along the cross-axis (vertically, in this case). */
    }
    
    .sidebar {
      flex-basis: 20%;        /* set width to 20% */
      background-color: aqua;
    }
    
    .content {
      flex: 1;                /* set width to whatever space remains */
      background: magenta;
    }
    <div class="outer-flex-container">
    
         <div class="header">HEADER</div><!-- main flex item #1 -->
    
         <div class="nested-flex-container"><!-- main flex item #2 -->
    
              <div class="sidebar">SIDEBAR</div><!-- inner flex item #1 -->
    
              <div class="content">MAIN CONTENT</div><!-- inner flex item #2 -->
    
         </div><!-- close inner flex container -->
    
    </div><!-- close outer flex container -->


    Revised Codepn

    09-10 11:53
    查看更多