问题
I am moderately familiar with Flex-box, but this issue has me baffled:
I am trying to create a flex-box layout that:
- Puts a footer at the bottom of the screen IF content is shorter than the screen (view-port)
- Puts footer at end of scrolling content IF content is longer than the screen (view-port)
I can seem to get one, or the other, but not both of these to work. A couple of goals:
- Achieve this, if possible, in CSS alone
- The header should remain fixed at the top of the screen, while the content has scrollable overflow
- The header bar will vary in size, so the solution should accommodate this
Codesandbox Demo of Issue
Thanks for any help
回答1:
Set min-height
to 100vh
of #wrapper
like
#wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
}
And alps you need to set margin
of body
to 0
to avoid scroll
body{
margin: 0;
}
For sticky header as per OP Requirement Please add theses styles along with the above one i mentioned (i just remove height as you said header is of dynamic height)
#header {
background-color: darkgray;
/* height: 64px; */
position: sticky;
top: 0;
}
So the final Styles you need to put inside demo.css
are as below
body {
background-color: #444;
margin: 0;}
#wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
}
#header {
background-color: darkgray;
/* height: 64px; */
position: sticky;
top: 0;
}
回答2:
Are you looking to scroll only content?. change these css only.
#mainContent {
display: flex;
flex-direction: column;
flex-grow: 1;
background-color: white;
height:100vh;
}
#footer {
background-color: red;
height: 64px;
position:fixed;
bottom:0;
}
回答3:
body {
background-color: #444;
position: relative;
margin: 0;
min-height: 100vh
}
#footer {
background-color: red;
height: 64px;
width:100%;
left: 0;
position: absolute;
bottom:0;
}
回答4:
There is a solution when we want our footer to be on the bottom of the screen even when the content of our flexbox wrapper is shorter than the height of our screen.
The solution is to create a div (we can call it spacer) just above the fotter and give it a css property flex: 1
(Which is a shortcut for flex-grow:1, flex-shrink:1 and flex-basis:0). If you think about it, what we want is to make our div spacer grow or shrink with the content.
In summary, I added:
CSS
.spacer {flex: 1;}
#wrapper {display: flex; flex-direction: column; min-height: 100vh;}
TSX
<div className="spacer" />
A complete example can be found here
来源:https://stackoverflow.com/questions/60489733/set-flexbox-min-height-to-fill-remaining-screen-in-scrolling-container