我非常喜欢 Flexbox 的想法,我用它来使我的网站具有响应能力。
但是现在我很困惑。
我想做的是:
我想让content-body
访问剩余空间。我尝试使用 height: 100%
但没有任何反应,然后我尝试将 height: 100%
给它的父 content-wrapper
然后它溢出了main-content
:
我想知道:
- 为什么会发生这种情况以及
- 如何克服它。
注意:该网站应该是响应式的。
我创建了一个很好的 jsFiddle 来解释我的情况。 http://jsfiddle.net/bqpxd3y4/2/
<body>
<div class="main-container">
<div class="main-header">
HEADER
</div>
<div class="main-content">
<div class="content-wrapper">
<div class="content-head">
Content Head
</div>
<div class="content-body">
CONTENT-BODY
</div>
</div>
</div>
<div class="main-footer">
FOOTER
</div>
</div>
</body>
CSS
@CHARSET "ISO-8859-1";
body,html{
margin:0;
width:100%;
height:100%;
//font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-family:"Trebuchet MS !important";
background-color:#00b3b3;
}
.main-container{
display:flex;
flex-direction:column;
flex-wrap:nowrap;
height:100%;
width:100%;
box-sizing:border-box;
}
.main-header{
background-color:#099;
height:10%;
}
.main-footer{
background-color:#099;
height:10%;
}
.main-content{
background-color:#fff;
height:100%;
display:flex;
flex-direction:row;
flex-wrap:nowrap;
}
.content-wrapper{
background-color:#80ccff;
margin:1em;
display:flex;
flex-direction:column;
height:100%;
}
.content-head{
background-color:red;
}
.content-body{
background-color:green;
height:100%;
}
最佳答案
有两件事:
- 您已为页眉和页脚指定了
高度:10%
。因此在定义主要内容的高度时,使用height: 80%
。这可以防止溢出。 - 使用
flex: 1
告诉 Flex 元素占用容器中的所有可用空间。
body,html{
margin:0;
height:100%;
background-color:#00b3b3;
}
.main-container{
display:flex;
flex-direction:column;
height: 100%;
/* width: 100%; */
box-sizing:border-box;
}
.main-header{
background-color:#099;
height:10%;
}
.main-footer {
background-color:#099;
height:10%;
}
.main-content {
background-color:#fff;
height: 80%; /* main content - less header - less footer */
display:flex;
}
.content-wrapper {
background-color: #80ccff;
margin: 1em;
display: flex;
flex-direction: column;
}
.content-head{
background-color:red;
}
.content-body{
background-color:green;
flex: 1;
}
<div class="main-container">
<div class="main-header">HEADER</div>
<div class="main-content">
<div class="content-wrapper">
<div class="content-head">Content Head</div>
<div class="content-body">CONTENT-BODY</div>
</div>
</div>
<div class="main-footer">FOOTER</div>
</div>
jsFiddle
在此处了解有关 flex
属性的更多信息:
- 7.1. The
flex
Shorthand ~W3C - 7.1.1. Basic Values of
flex
~W3C -
flex
definition 〜MDN -
flex
definition ~ CSS 技巧
关于html - 如何让div在不使用固定高度值的情况下访问剩余空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36221570/