Home > Net >  make content scrollable within a sizeble div
make content scrollable within a sizeble div

Time:06-02

I have a site (always 100% height), with a menu that grows based on the number of items in the menu. Now i put a max-height on the div that holds the menu, to make sure it doesn't move out of my screen. I used max-height: calc(100% - 20px);

All works fine so far..

Now I want my content to scroll when i got too many items.. And I've been doing this for a full day now and can't figure it out.

I made a testcase here https://jsfiddle.net/ym5pgtdr/24/

html,
body {
  height: 100%;
  padding: 0;
  margin: 0;
  border: 0;
}

.menu {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 300px;
  background-color: purple;
  max-height: calc(100% - 20px);
}

.title {
  margin: 5px;
  padding: 5px;
  height: 50px;
  background-color: red;
}

.body {
  height: *;
  margin: 5px;
  padding: 5px;
  background-color: green;
  overflow: auto;
}
<div >
  <div >Title here</div>
  <div >
    lots of content here.<br />
  </div>
</div>

I know scrolling only works when the div with the 'overflow' attribute has a calculated height (meaning it should either have a height property or the browser can derive the size of the div somehow). But how does that work in this case??

CodePudding user response:

You're almost there.

Apply overflow: hidden on the .menu-element, so its contents don't overflow out of the container.

Apply overflow-y: scroll (vertical overflow) on the .menu-element, as that's the element that's going to have the overflowing content.

Optionally you could set a max-height on the .body-element if you don't want it to stretch completely.

html,
body {
  height: 100%;
  padding: 0;
  margin: 0;
  border: 0;
}

.menu {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 300px;
  background-color: purple;
  height: 100%;
  max-height: calc(100% - 20px);
  overflow: hidden;
}

.title {
  margin: 5px;
  padding: 5px;
  height: 50px;
  background-color: red;
}

.body {
  height: 100%;
  margin: 5px;
  padding: 5px;
  background-color: green;
  overflow-y: scroll;
}


/* For demo purpose */

.body>div {
  padding: 30px;
}
<div >
  <div >Title here</div>
  <div >
    <div>lots of content here.</div>
    <div>lots of content here.</div>
    <div>lots of content here.</div>
    <div>lots of content here.</div>
    <div>lots of content here.</div>
    <div>lots of content here.</div>
    <div>lots of content here.</div>
    <div>lots of content here.</div>
    <div>lots of content here.</div>
    <div>lots of content here.</div>
    <div>lots of content here.</div>
  </div>
</div>

CodePudding user response:

Try these classes for your menu and body:

.menu {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 300px;
  background-color: purple;
  max-height: calc(100% - 20px);
  overflow: auto;
}

.body {
  max-height: 100%;
  margin: 5px;
  padding: 5px;
  background-color: green;
}
  • Related