Search code examples
csshtmlposition

Create a scrolling div between two fixed div elements


I'm kind of new to positioning divs how I want them in a website, so I hope someone can help here. What I'm trying to get is a sandwich-type set up with a scrolling content in the middle of two divs. Such that I have a header div and a footer div, both of which have to stay static on the page. Then, between them, I have to have a content div that fills the space between the two fixed divs and have the ability to scroll on it's own. How would I go about building something simple like this? Or is this not simple at all?

Update: I created a fiddle that I think is ALMOST what I want. I have the header and footer staying static on the page. However, I'm having to trick the top margin of the main div so that it's content starts right after the header. The only problem I still have, really, is that the end of the content is being cut off at the bottom by the footer. I need to see the entire content.

Fiddle: http://jsfiddle.net/fgskS/18/

Thank you!


Solution

  • Simply set the height of the consecutive elements to equal 100% and set your content DIV to scroll on the Y-axis:

    <header>
        <h1>Sandwich Layout</h1>
    </header>
    <div id="main" role="main">
    
    </div>
    <footer>
        Footer stuff here
    </footer>
    
    html,
    body { height: 100%; margin: 0; padding: 0; } /* This is important */
    
    header,
    footer { background: #ccc; height:20%; }
    
    #main { height: 60%; overflow-y:scroll; }
    

    Fiddle: http://jsfiddle.net/kboucher/3E8Gg/

    2020 UPDATE:

    HTML:

    <header>
        <h1>Sandwich Layout</h1>
    </header>
    <div class="main" role="main">
      <div class="fake-height">Content here</div>
    </div>
    <footer>
        Footer stuff here
    </footer>
    

    CSS:

    body,
    html {
      height: 100vh;
      overflow: hidden;
      margin: 0;
      padding: 0;
    }
    
    body {
      display: flex;
      flex-direction: column;
    }
    
    header,
    footer {
      background: #eee;
      padding: 1rem;
    }
    
    .main {
      flex: 1 0 auto;
      height: 0; // prevents flex box expanding out of view-height
      overflow-y: auto;
      padding: 1rem;
    
      .fake-height {
        height: 1000px;
      }
    }
    

    https://codepen.io/kboucher/pen/dyomxWN