0
\$\begingroup\$

For a template such as:

Scroll

I'm using the following approach

  • Get the height of the viewport via javascript (Let's say 500px)
  • Deduct the header and footer height from it (Let's say header and footer are 50px each. So the end result will be 400px)
  • Apply the end result as height of the main content div via javascript
  • Use overflow-y:scroll property on the main content div via CSS

This works as expected but I was hoping there might be a better way to achieve the same. I'm thinking only via CSS, if possible.

The code I'm using is:

<!-- javascript -->
var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var to_apply_height = height - 50 -50; // header and footer height
document.getElementById('main_content').style.height = to_apply_height+'px';

<!-- css -->
#main_content{
overflow-y:scroll;
}
\$\endgroup\$
2
\$\begingroup\$

You can use flexbox. This works in all modern browsers, and will also make it responsive.

.wrapper {
  /* Makes the wrapper fill the entire screen */
  position: fixed;
  top: 0;
  height: 100%;
  left: 0;
  width: 100%;
  /* The important bit */
  display: flex;
  flex-direction: column;
}

.main {
  /* Makes the main content take up the remaining space */
  flex: 1;
  overflow-y: scroll;
}

.header, .footer {
  height: 50px;
}

JSFiddle

\$\endgroup\$
0
\$\begingroup\$

Try to use CSS3's calc() function with the vh unit, like this:

#main_content{
  height: calc(100vh - 100px);
  overflow-y:scroll;
}
\$\endgroup\$
  • \$\begingroup\$ What about browser compatibility? I don't suppose it's quite good. \$\endgroup\$ – asprin Jan 23 '17 at 6:38
  • \$\begingroup\$ @asprin I don't think it is possible with older browsers in a CSS only manner. \$\endgroup\$ – Usagi Miyamoto Jan 23 '17 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.