我正在尝试创建一个顶部有标题的布局,其下方是侧边栏和主要内容。
我想让侧边栏和内容 View 占据标题留下的垂直空间。问题是 header 可以动态调整大小,因此我无法执行 calc()
。我的解决方案是使用 flexbox 方案。
我将视口(viewport)水平分为两部分。一个是标题,一个是侧边栏和主要内容的包装。
侧边栏向左浮动并指定宽度的百分比,内容向右浮动并指定其余部分。
问题是我试图让侧边栏始终是包装器高度的 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>
最佳答案
没有必要:
height
、min-height
或calc
在您的 flex 元素上- 绝对定位
- 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 -->
关于html - 使第二行的 flex 元素占用容器的剩余高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36167253/