'Force to scroll overflowing item in flexbox

Im making a container with 3 cards. Each card (brown-ish color in example) has a header with title (sand-buiscuit color) and content (blue one).

What I want to acheive is when the cards are closed (click on header in example), the content (blue) is transitioning to height 0, and so the only visible part is header.

Also when the card is open I want to show the available content but only then, when there is enough available space in container (green).

When 3 cards are open, they have the same height (expand evenly in container), and remaining content (blue) is scrolled.

Is it possible to make? I prepared a demo codesandbox



Solution 1:[1]

I made a small code example using styled-components (just because i like it), you can easily change it to regular react components with css, but this demonstrates the idea.

I created 3 boxes, each box has a default height(40px) and after clicking (which opens it) its height is set to: 100%.

Wrapping all of this boxes with flex container does the trick.

import styled from 'styled-components';
import React, { useState } from 'react';

const MyComponent = () => {
  return (
    <Container>
      <BoxContainer height={100} number={1} />
      <BoxContainer height={100} number={2} />
      <BoxContainer number={3} />
    </Container>
  );
};

export default MyComponent;

const Container = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  width: 200px;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  background-color: blue;
`;

const BoxContainer = ({ number, height = '100' }) => {
  const [open, setOpen] = useState(false);

  return (
    <Box style={{ height: open ? '100%' : '40px' }} onClick={() => setOpen(!open)}>
      Box: {number}
      {open && <p>Content</p>}
    </Box>
  );
};

const Box = styled.div`
  width: 100%;
  overflow: scroll;
  background-color: #00b8a2;
  border: 1px solid red;
`;

sandbox example here: https://codesandbox.io/s/boxes-fill-container-evenly-when-opened-btlvb

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GiL Itzhaky