Home > Blockchain >  html/css flex: How to prevent item in container exceed parent container height?
html/css flex: How to prevent item in container exceed parent container height?

Time:10-03

I have very simple layout:

 --------------- 
|    Header     |
 --------------- 
|       |       |
|       |       |
| Item1 | Item2 |
|       |       |
|       |       |
 --------------- 

Which should be 100% of page height and Item2 should be vertically scrollable (Item 1 have fixed size and do not influence height).

I am trying to use flexbox. The root container is flex column which holds header and child flex container. The child container holds Item1 and Item2 and has flex: 1 to force items grows till bottom of the page.

The problem is, that when adding content to Item2 it's parent container starts to grow in height and exceed root container height! So scrollbar appears for the page, but I need only Item2 should be scrollable.

Is there any method to prevent this, only using flex features, not involving height, max-height? If it's not possible what is correct settings for heights in this situation?

<div style="display: flex; flex-direction:column; height: 100vh;">

  <div>Hello Flex!</div>

  <div style="flex: 1; display: flex">
    <div style="flex: 1">
      1
    </div>
    <div style="flex: 1; overflow: auto">
      2<br>2<br>2<br>very long content, should be scrollable and NOT stretch parent.
    </div>
  </div>

</div>

CodePudding user response:

Here is one possibility using CSS Grid Layout and flexbox. The height of the header was set at 200px but it could be anything or a relative unit.

<!DOCTYPE html>
<html>
<head>
  <title>layout</title>
  <style type="text/css">
    body {
      margin: 0;
      padding: 0;
    }
    #grid {
      display: grid;
      background: rgba(255, 255, 255, 0.5);
      grid-template-rows: 200px calc(100vh - 200px);
    }
    #header {
      background: blue;
    }
    #cols {
      display: grid;
      grid-template-columns: 1fr 1fr;
      background: green;
    }
    #colA {
      background: yellow;
    }
    #colB {
      display: flex;
      flex-direction: column;
      overflow-y: auto;
      background: orange;
    }
    #content {
      padding: 1200px 20px;
    }
  </style>
</head>
<body>
  <div id="grid">
    <div id="header"></div>
    <div id="cols">
      <div id="colA"></div>
      <div id="colB">
        <div id="content">
          colB content
        </div>
      </div>
    </div>
  </div>
</body>
</html>

See it on codepen.

CodePudding user response:

To solve this with flexbox you need to wrap the box you want to scroll and add overflow-x: hidden; to the wrapping container. To fix some extra space use the calc() method. This happens, when is used height: 100vh; on a scrollable element.

  • Related