Magalie Linda Magalie Linda - 9 months ago 22
CSS Question

Force scroll on content element

I have been searching far and wide, but I can't find it on the interwebs.

This is my problem.

I'd like to have my

<main>
element to have an
overflow-y:scroll
.
No scrollbar on the body, but on the main.

I have made a pen to illustrate: http://codepen.io/magalielinda/pen/rymzBG/

As you can see the scrollbar shows, but it's not scrolling. Pourquoi? And how do I make it so it does scroll?

Here's my demo html for those of you that can answer it more easily this way:

<main>
<div class="content__container">
</div>
</main>


and demo css:

body {
overflow: hidden;
height: 100%;
}

main,
.content__container {
height: 100%;
}

main {
overflow-y: scroll;
background-color: red;
border: 1px solid blue;
}

.content__container {
max-width: 200px;
margin: 0 auto;
background-color: aqua;
height: 1000px;
}


Thanks so much!

Answer Source

height: 100% will be 1000px to accommodate the contents of .content__container. If you inspect main, .content__container, body, they're all 1000px tall. So all of the content is simply overflowing body and you've set overflow: hidden on body - no scroll bar.

You just need to limit the height of main so that there is overflow to scroll through. If you use 100vh instead, things scroll as you would expect.

body {
  overflow: hidden;
  height: 100%;
}

main {
  height: 100vh;
  overflow-y: scroll;
  background-color: red;
  border: 1px solid blue;
}

.content__container {
  max-width: 200px;
  margin: 0 auto;
  background-color: aqua;
  height: 1000px;
}
<main>
  <div class="content__container">
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
    foobar<br>
  </div>
</main>