Fluid sticky footer with flex

2020-04-26 05:01发布

问题:

I am trying to make footer at the bootom with flex as described in this question How to make a fluid sticky footer

the answer with adding to the body

body {
     padding: 0; margin: 0;
     display: flex;
     min-height: 100vh;
     flex-direction: column;
}

and main

main {
     flex: 1;
     padding: 1em;
}

works fine if header, main and footer is one after another and all is inside body

but what if header is outside like in this template

<body>
   <div id="headerDiv"> This is header </div>
   <div id="mainDiv"> 
       <div id="contentDiv"> This is content </div>
       <div id="footerDiv"> This is footer </div>
   </div>
</body>

then if I add body class to body html element and main class to contentDiv it does not work if I add body class to mainDiv and main class to contentDiv then it almost works but my footer is lower of height of the headerDiv and there is scroll, how to avoid that ?

回答1:

What if ?

the second container can be a flexbox too ,

Use the same CSS flex technic applied to body and #mainDiv to #mainDiv and #contentDiv, minus height since flex:1; is already sizing #mainDiv.

body,
#mainDiv  {
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
}

body {
  min-height: 100vh;
}
#mainDiv,
#contentDiv {
  flex: 1;
}

/* see them */
#headerDiv,#footerDiv {background:yellow;padding:1em}
#mainDiv {background:pink;}
<div id="headerDiv"> This is header </div>
<div id="mainDiv">
  <div id="contentDiv"> This is content </div>
  <div id="footerDiv"> This is footer </div>
</div>



回答2:

Try using a flex container on the #mainDiv with justify-content: space-between.

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: orange;
  margin: 0;
}

#mainDiv {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
<body>
  <div id="headerDiv"> This is header </div>
  <div id="mainDiv">
    <div id="contentDiv"> This is content </div>
    <div id="footerDiv"> This is footer </div>
  </div>
</body>



标签: html css flexbox