Steps to create a scrollable container within a div that occupies the entire available space within the div

One of the sections in my div is a scrollable list that needs to adjust its size dynamically based on the screen size.

I am struggling with finding a solution that allows the scrollable area to occupy all the remaining space of the parent without specifying a fixed height. If I set the height to 100%, I lose the ability to scroll, and if I specify a fixed height, it won't be responsive to different screen sizes.

How can I make the scrollable section fill in the rest of the space within the parent div?

Below is an example code snippet illustrating the issue:

const App = () => {

  return (
    <div className="container">
      <div>
        <h2>My Content</h2>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua.
        </p>
        <h3>Scrollable section that must fill in the rest of the space</h3>
        <div className="scrollable-div">
          {[...Array(50).keys()].map((_, index) => (
            <div>item {index}</div>
          ))}
        </div>
      </div>
    </div>
  );
}


ReactDOM.render(
    <App />,
    document.getElementById('app')
);
.container {
  height: 500px;
  border: 2px solid black;
  overflow: hidden;
}

.scrollable-div {
  overflow: auto;
  border: 3px solid red;
  /*
  this all works fine, but I need the scroll section to go all the way to the end of the parent div,
  regardless of the screen size. How can I do this without setting a fixed height here?
  */
  height: 250px;
  /*
    the alternative, which would allow this div to expand all the way down to the reminder of the parent
    is set height to 100%, however then I lose my ability to scroll.
  */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Answer №1

When you run the snippet, click on 'full page' and then resize your browser window to see the dynamic height of the scrolling area. This has only been tested in Chrome.

const App = () => {

      return (
        <div className="container">
          <div className="inner">
            <h2>My Content</h2>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
              eiusmod tempor incididunt ut labore et dolore magna aliqua.
            </p>
            <h3>Scrollable section that must fill in the rest of the space</h3>
            <div className="scrollable-div">
              {[...Array(50).keys()].map((_, index) => (
                <div>item {index}</div>
              ))}
            </div>
          </div>
        </div>
      );
    }


    ReactDOM.render(
        <App />,
        document.getElementById('app')
    );
.container {
      display: flex;
      flex-direction: column;
      border: 2px solid #2B3239;
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }

    .inner {
      padding: 12px;
      background: #EFF2F5;
      min-height: 0;
      display: flex;
      flex-direction: column;
    }

    .scrollable-div {
      background: white;
      border: 2px solid #FF6F6F;
      flex-grow: 1;
      overflow: scroll;
      padding: 12px;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js">

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 are the best methods for capturing audio directly from a web browser?

One of my clients is looking to allow users to record a message directly from their browser and then save it as an audio file like WAV. What would be the most effective approach for achieving this - Flash, Java, or HTML5? The goal is to find a method that ...

A collection of 64-bit integer values stored in a Hashtable

I am in search of a solution to enable O(1) lookup for binary quadkeys I understand that true hashtables do not exist in JavaScript, and the alternative is using objects with o(1) lookup using their properties. However, the issue lies in the fact that the ...

Starting multiple timers in sequence using jQuery

I'm working on this code snippet var duration = 60 * $(".duration").val(), display = $(".timer"); startTimer(duration, display); function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function () { ...

Unable to open file after downloading via AJAX

I am facing an issue while trying to download a file using an Ajax request. Although the file is successfully downloaded, I am unable to open it. I am seeking assistance with the provided details below. Thank you. On a JSP page, there is a list ...

JavaScript logic for playing the hangman game

I am working on creating a hangman game and I need some guidance on developing the logic. I am new to programming, so I would like to keep it simple by using basic syntax. One thing I'm trying to figure out is how to display dashes (-) that represent ...

The Mat-slide-toggle resembles a typical toggle switch, blending the functionalities of

I am facing an issue with a `mat-slide-toggle` on my angular page. Even though I have imported the necessary values in the module, the toggle is displayed as a normal checkbox once the page loads. HTML: <div style="width:100%;overflow:hidden"> < ...

Is there a potential issue with spreading on IE 11 in (Webpack, VueJS)?

Encountering an error on Internet Explorer 11: https://i.sstatic.net/zGEeK.png https://i.sstatic.net/FKSUs.png Reviewing my webpack and babel configurations: webpack configuration const path = require('path'); const webpack = require('we ...

What is the method to retrieve the file name when a user chooses a file using <input type="file" />?

In the past, I've encountered similar inquiries that have remained unresolved due to security concerns. However, I recently discovered that HostMonster has effectively tackled this issue when I submitted a ticket and attached a file through their bac ...

Is there a CSS selector that allows me to exclude the final two child elements?

Is there a way to apply bottom-border to certain div elements within their parent, excluding the last two? It's important to note that the number of child elements can vary: <div id="parent"> <div> One </div> <div> Tw ...

Using React to fetch data from an API

Imagine having the following fetch request. useEffect(() => { fetch("apiUrl", { headers: { "Content-Type": "application/json", Accept: "application/json", }, }) .then((re ...

What is the best way to retrieve a value from async/await functions?

async function fetchNetworkStatus() { const network = await Network.getConnection(); setConnection(network.isConnected); console.log(connectionStatus); if (network.isConnected) { return true; } else { ...

Accessing a different function within an array of functions

I am currently using require.js and have a collection of functions that I utilize in various locations. The way I define these functions is as follows: define(function (require) { "use strict"; var $ = require('jquery'); var Usefu ...

Improprove Google PageSpeed score - must resolve

My mobile website is loading incredibly slow, despite my attempts to improve the speed using Google PageSpeed insights. Unfortunately, I'm having trouble interpreting the screenshot and identifying what changes need to be made. Is there anyone who c ...

Expanding and collapsing UI elements within an ngRepeat loop in AngularJS

I have been attempting to incorporate collapsible panels within an ngRepeat loop. Below is the code I have been using: <div class="panel panel-default" ng-repeat="element in elements"> <div class="panel-heading"> ...

How can you link a Razor Function to a JavaScript Variable?

Trying to incorporate a Razor C# Function into a JavaScript Function has been a challenge for me. While it's simple to do in HTML, I'm encountering compilation errors when attempting it in JavaScript. I've experimented with the <text> ...

issue with scrolling using the ideal scrollbar

Can someone help me figure out how to integrate the 'perfectScrollbar('update')' function with my Angular.js code? $http.get('demo/json/test.json'). success(function(data, status, headers, config) { $scope.items = d ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

What is the best way to utilize an HTML form for updating a database entry using the "patch" method?

I have been attempting to update documents in my mongoDB database using JavaScript. I understand that forms typically only support post/get methods, which has limitations. Therefore, I am looking for an alternative method to successfully update the documen ...

Exploration of how modals are constantly refreshing with each modal switch

Whenever a new modal pops up asking users questions on a car estimate site, the entire component and its child components re-render. Although this behavior is acceptable, the main issue arises when submitting the problems modal, causing the complete comp ...

Using jQuery to conceal the elements within a div

Hi there! I am just starting out with programming and JavaScript, and I have a fun idea for a simple memory game involving numbers. Here's how it works: when the user clicks on a button, numbers will be revealed for 5 seconds, and then they will hide ...