Two vertical containers dynamically adjusting their height together

I am facing a challenge with two containers that need to share the height of their parent element. The second container is added dynamically when needed, and both containers may contain a lot of content, requiring scroll capabilities.

While I have a solution for creating a 50/50 split between the containers, I am exploring if it's possible to dynamically adjust their heights based on content.

.wrapper__container {
  display: flex;
  height: 100%;
  max-width: 100%;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inside__container {
  flex: 0 0 100%;
  max-width: 100%;
  overflow-y: auto;
}

This snippet represents part of the wrapper component's render method:

render() {
  const maxHeight = this.state.showDetails ? '50%' : '100%';
  const minHeight = this.state.showDetails ? '50%' : '100%';
  return (
    <div className="wrapper__container">
      <Config 
        itemsGreen={this.state.itemsGreen}
        itemsRed={this.state.itemsRed}
        changeItemCount={this.changeItemCount}
      />
      <Container
        itemCount={this.state.itemsGreen}
        className="inside__container"
        style={{
          backgroundColor: 'green',
          maxHeight,
          minHeight
        }}
        onClick={this.handleClick}
      />
      {this.state.showDetails && <Container
        itemCount={this.state.itemsRed}
        className="inside__container"
        style={{ 
          backgroundColor: 'tomato',
          maxHeight,
          minHeight
        }}
      />}
    </div>
  )
}  

I have created a CodePen where you can test the behavior by adjusting the item counts. Clicking on the green container will reveal the red one.

An ideal solution would be to limit the green container to a maximum height of 50% and allow the red container to occupy the remaining space. For instance, if the green container is only 20%, the red container should take up 80%.

In an optimal scenario, achieving this dynamic height adjustment should not require JavaScript calculations, but I am open to suggestions using either React or vanilla JavaScript.

The target browser compatibility required is IE11.

Edit: I have also included a new Pen which demonstrates the desired flexible behavior when dealing with fewer items.

Answer №1

When the outer container is rendered, you must calculate the height of the container and then divide it by two. Afterwards, this number should be set as the height for each internal div. Here's an example using jQuery:

var $two = $('<div id="two"></div>');
var $three = $('<div id="three"></div>');
$('#container').append($two);
$('#container').append($three);
var h = $('#one').height();
console.log((h/2)-1)
if($('#two').height() < ((h/2)-1)) {
  $('#three').height( ( h-$('#two').height() ) - 1 );
} else {
   $('#two').height((h/2)-1);
   $('#three').height((h/2)-1);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to maintain a Photo's Aspect Ratio using just HTML and CSS?

Although I've been a bit slow to get on board with Responsive Design, I finally understand how it works. However, there's one specific issue that has stumped me - something I don't recall ever encountering in my 10 years of website developme ...

How can I show the Material-UI InputAdornment Icon only when it is selected?

Looking for a way to display the Material-UI Icon adornment only when the user selects the text field in this sandbox example: https://codesandbox.io/s/material-demo-w385h Code: <TextField className={classes.margin} id="input-with-icon-textfield" ...

Is it possible to achieve the expected outcome at the end of an arrow function without using the filter method?

Here's the coding section - {data?.results ?.filter(item => { if (searchTerm === '') { return item; } else if ( item.title .toLowerCas ...

Adjust a CSS variable with a simple click

I have a challenge where I want to double the value of an element's property every time it is clicked, using CSS variables. Here's what I have tried: #circle_1 { width:50px; height:50px; width: var(--size_1, 50px); heig ...

The module import in the JavaScript file is malfunctioning

As part of a small learning project, I discovered that when I include an import in a js script, it seems to be ignored and not executed. I'm unsure if the issue lies in the code itself or in WebStorm. Even with a simplified example that I tried, it d ...

Error: Attempting to assign a value to the propTypes property of the Settings function resulted in a TypeError

I am encountering an issue where the prop types are functioning properly with a normal React component but failing with a Redux connected component. Here are the error details: Uncaught TypeError: Cannot set property propTypes of function Settings(prop ...

CSS - setting the background-image property is not displaying the image

.main_banner { background-image: url("../images/main_banner.png"); width: 100%; height: auto; } <!DOCTYPE html> <html> <heading> <title> ********** </title> <link rel="sty ...

Bcrypt installation continues to be problematic, despite trying multiple solutions

I have spent months troubleshooting, but I cannot seem to npm install bcrypt no matter what methods I try. Attempts include sudo npm install bcrypt, brew install bcrypt, reinstalling node, modifying JSON files, and even trying alternatives like bcryptjs. ...

Scroll horizontally through the number field in Chrome

I have configured a number input field with the text aligned to the right. Scenario: While testing, I discovered that selecting the entire text or using the middle mouse button to scroll within the input field allows for a slight leftward scrolling of ab ...

Is it possible to dynamically load a specific div when the page loads, relying on the

I am using JQuery SlideUp and slideDown methods to toggle the visibility of panels. How can I load or display the first record's contact information as a default? Currently, it loads blank because I set the panel's display property to none: < ...

Populating the table with data through a repetitive process

Is there a way to automatically populate a table using values from an array? <table> <thead> <tr> <div ng-repeat="n in range" > <th> {{vm.data.list[n].temp.day}} {{vm.symbal}} ...

The appearance of the React user interface in my app does not match what is displayed in the inspect element tool

Strange issue at hand. The progress bar in question appears like this: 1 export default function PercentageBar(props) { 2 return ( 3 <div className="w-full h-1 my-1 bg-stone-200"> 4 <div className={`h-1 bg-orange- ...

How to generate a hyperlink in JQGrid

Trying to create clickable links in all cells of a column within my JQgrid. These links should call a javascript function passing the cell value for server-side queries. After researching on html link column in jqGrid, I have attempted the following: colM ...

Struggling to make bootstraps' responsiveness function properly

I've been struggling to achieve responsiveness on a webpage I'm working on, but despite trying different approaches including wrapping the table as suggested in another forum post, I still can't get it to work. Could someone please help me i ...

Adjusting the background opacity of three.js to .5

I'm currently experimenting with changing the background of the canvas in three.js to have an opacity of 0.5. I know that I can achieve a completely transparent background using new THREE.WebGLRenderer( { alpha: true } );. However, this is not the eff ...

I'm noticing that my CSS is behaving differently than expected. Despite setting position: absolute, the output is displaying as inline-block instead of block. Why is this happening

div { width:200px; height:200px; position: absolute; } .first-container { background-color: #9AD0EC; } .second-container { background-color: red; left: 200px; } .third-container { background-color: blue; left:400px; } Despite setting th ...

I am facing an issue with the Ionic Framework where the Javascript function for JWPlayer only works after the page is reloaded. Can anyone help

I'm currently troubleshooting the use of JWPlayer for streaming videos in an Ionic app. However, I've encountered a problem. The player only seems to load when I refresh the page, rather than when I navigate through the list of videos. Here is ...

What is the best way to construct an AJAX call that includes two sets of POST data?

I'm currently working on a project that involves sending WebGL frames/screenshots to a server for saving to the hard drive and later merging them into a video file. I came across this helpful resource: Exporting video from WebGL Without delving too m ...

Error message displayed for invalid date format in Material UI (dateTime picker) after form submission

I recently integrated the Material Ui DateTime picker into my form. However, upon submitting the form, I encountered the following error: Invalid Date Format Image In my React app, I am utilizing JSON Server to store data. Displayed below is the outpu ...

Iterate through the array and generate a ListItem component for every element

Currently, I am facing an issue where only the ListSubheader is being displayed in my code. Despite passing an array named tools and trying to loop through it to create ListItem elements based on each item's properties, no buttons are displaying. I su ...