Adjustable scrollbar for varying content heights

Below is the HTML structure that I am working with:

<div id="body">
    <div id="head">
        <p>Dynamic height without scrollbar</p>
    </div>
    <div id="content">
        <p>Dynamic height with scrollbar</p>
    </div>
    <div id="foot">
        <p>Fixed height without scrollbar</p>
    </div>  
</div>

The goal is to keep all three parts inside the main part (#body) without overflowing. To achieve this, a scroll bar should be present in the middle section.

I attempted different CSS options like below:

#content{
    border: red solid 1px;
    overflow-y: auto;
}

And also tried this:

#content{
    border: red solid 1px;
    overflow-y: auto;
    height: 100%;
}

However, none of these solutions seem to work as intended.

An example demonstration can be found on JSFiddle.

Is it possible to achieve this using only CSS and HTML? Ideally, I would like to avoid involving Javascript if possible.

Answer №1

Flexbox provides a contemporary solution that allows achieving dynamic sizes without relying on fixed heights or JavaScript.

To implement this, simply use

display: flex; flex-direction: column;
on the container element and flex-shrink: 0; on the header and footer divs:

Here's the HTML code:

<div id="body">
    <div id="head">
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>  
    </div>
    <div id="content">
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        ...
        <p>Dynamic size with scrollbar</p>
    </div>
    <div id="foot">
        <p>Fixed size without scrollbar</p>
        <p>Fixed size without scrollbar</p>
    </div>  
</div>

The CSS styling is as follows:

#body {
    position: absolute;
    top: 150px;
    left: 150px;
    height: 300px;
    width: 500px;
    border: black dashed 2px;
    display: flex;
    flex-direction: column;
}
    
#head {
    border: green solid 1px;
    flex-shrink: 0;
}

#content{
    border: red solid 1px;
    overflow-y: auto;
}

#foot {
    border: blue solid 1px;
    height: 50px;
    flex-shrink: 0;
}

Snippet of the CSS and HTML code:

#body {
  position: absolute;
  top: 150px;
  left: 150px;
  height: 300px;
  width: 500px;
  border: black dashed 2px;
  display: flex;
  flex-direction: column;
}

#head {
  border: green solid 1px;
  flex-shrink: 0;
}

#content {
  border: red solid 1px;
  overflow-y: auto;
}

#foot {
  border: blue solid 1px;
  height: 50px;
  flex-shrink: 0;
}
<div id="body">
  <div id="head">
    <p>Dynamic size without scrollbar</p>
    <p>Dynamic size without scrollbar</p>
    <p>Dynamic size without scrollbar</p>
  </div>
  <div id="content">
    <p>Dynamic size with scrollbar</p>
     ...
    <p>Dynamic size with scrollbar</p>
  </div>
  <div id="foot">
    <p>Fixed size without scrollbar</p>
    <p>Fixed size without scrollbar</p>
  </div>
</div>

Answer №2

I encountered a similar problem with the PrimeNG p_Dialog content, but I was able to resolve it by applying the following style to the contentStyle:

height: 'calc(100vh - 127px)'

Answer №3

Here is a handy solution:

style="height: 150px; max-height: 300px; overflow: auto;"

Set a fixed height to establish the default size, allowing a scroll bar for accessing the full height.

Answer №4

 <div id="slide">
    <p>Feel free to include more content</p>
 </div>

This is the styling code

#slide {
   overflow-y:scroll;
   height:auto;
   max-height:250px;
   border:2px solid black;
   width:350px;
 }

Check out the demonstration JSFIDDLE

Answer №5

In order to set a specific height, it is important to define a fixed value instead of using a percentage since there needs to be a reference point for comparison. For example, setting height=100% would prompt the question: 100% of what?

Check out the updated fiddle here:

http://jsfiddle.net/9XyZb/7/

Answer №6

Expanding on @mtyaka's suggestion of utilizing flexbox, if your scrollable content is nested deep within the DOM structure, it is necessary to apply overflow: auto/hidden to all parent elements until a fixed height is established.

Check out this jsfiddle for an example: https://jsfiddle.net/rohilaharsh/cuazdnkh/1/

Here is the HTML code snippet:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Container</title>
</head>
<body>
    <div class="one">
    One
        <div class="two">
    Two
            <div class="three">
      Three
                <div class="table">
          Table
                    <div class="header">Table Header</div>
                    <div class="body"> [content truncated for brevity] </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

And here is the CSS code snippet:

html {
  height: 100%;
}

html, body, .one,.two,.three,.table {
  display: flex;
  flex-direction: column;
  
  /* important */
  overflow: hidden;
  
  flex: 1;
  margin: 0;
}

.body {
  width: 200px;
  overflow: auto;
}

Answer №7

An efficient method using minimal JS and CSS to adjust padding: http://jsfiddle.net/benjamincharity/ZcTsT/14/

var headerHeight = $('#header').height(),
    footerHeight = $('#footer').height();

$('#content').css({
  'padding-top': headerHeight,
  'padding-bottom': footerHeight
});

Answer №8

By utilizing display grid, it is possible to dynamically adjust the height of each section.

#body{
  display:grid;
  grid-template-rows:1fr 1fr 1fr;
}

To achieve the desired results, simply add the code above.

In cases where multiple levels of grids are used and CSS does not restrict your #content to 1fr, you can utilize the following:

#content{
  max-height:100%;
}

Answer №9

I'm not sure if this is correct, but could this be the solution to your issue?

The only change I made was to adjust the CSS property to overflow-y: scroll;

#wrapper{
    border: blue solid 1px;
    overflow-y: scroll;
    height: 200px;
}

Update:

You may want to consider using percentage values, like demonstrated in this example: http://example.com

Here is the corresponding CSS code:

#header {
    position: fixed;
    top: 20px;
    left: 20px;
    height: 10%;
    width: 80%;
    border: black dashed 2px;
}    
#main {
    border: green solid 1px;
    height: 60%;
}
#footer{
    border: red solid 1px;
    overflow-y: scroll;
    height: 30%;
}

Answer №10

Try out the following CSS code for styling:

#header {
    border: blue solid 1px;
    height: auto;
}    
#main-content {
    border: orange solid 1px;
    overflow-y: auto;
    height: 200px;       
}

Answer №11

If you're feeling adventurous, try playing around with viewport measurements in your CSS:

Viewport-percentage lengths allow you to set values as a percentage relative to the size of the initial containing block, which is based on either the viewport's size or the visible area of the page.

Check out more information on this topic on Mozilla's CSS length documentation

Specifically, take note of vh and vw, which correspond to a percentage of the height (width) of the viewport's initial containing block (the visible document area).

You can also experiment with vmin and vmax to obtain the smaller or larger of the viewport dimensions.

Answer №12

By following @mtyaka's example, I successfully triggered a resize of the content div using window.requestAnimationFrame in JavaScript. If you're looking to fill empty spaces on a page with 100% height without specifying a fixed height, this solution might be just what you need.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title></title>
        <style type="text/css">
            html {
                height: 100%;
                max-height: 100%;
                min-height: 100%;
                display: flex;
                flex-direction: column;
            }

            body {
                display: flex;
                flex-grow: 1;
                flex-direction: column;
            }

            #body {
                border: black dashed 2px;
                display: flex;
                flex-direction: column;
                flex-grow: 1;
            }

            #head {
                border: green solid 1px;
                flex-shrink: 0;
            }

            #content {
                flex-grow: 1;
                border: red solid 1px;
                overflow-y: auto;
            }

            #foot {
                border: blue solid 1px;
                flex-shrink: 0;
            }
        </style>
    </head>
    <body>

        <div id="body">
            <div id="head">
                <p>Dynamic size without scrollbar</p>
                <p>Dynamic size without scrollbar</p>
                <p>Dynamic size without scrollbar</p>
            </div>
            <div id="content">
                <p>Dynamic size with scrollbar</p>
                <p>Dynamic size with scrollbar</p>
                ...
            </div>
            <div id="foot">
                <p>Fixed size without scrollbar</p>
                <p>Fixed size without scrollbar</p>
            </div>
        </div>;

        <script type="text/javascript">
            window.requestAnimationFrame(function () {
                document.getElementById('content').style.height = '100px';
            })
        </script>

    </body>
    </html>

This is the exact solution I was looking for when I came across this post (among many others).

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

The concept of AJAX send function and toggling button visibility

I am facing a challenge with a textarea and send button on a panel that is displayed after entering the first character. The visibility of the button is controlled by the isButtonVisible() method. Once clicked, it sends the text from the textarea using the ...

What is the best method for choosing all elements located between two specific elements?

If I have the following HTML code, what CSS selector can I use to target all elements between #one and #two without using jQuery? <p id="one"></p> <p></p> <p></p> <p></p> <p></p> <p></ ...

Tips for allowing divs to be dragged and resized within table cells and rows

UPDATE I believe that utilizing Jquery is the most appropriate solution for resolving my issue with the demo. Your assistance in making it work would be greatly appreciated. Thank you. My goal is to develop a scheduler application. https://i.sstatic.net ...

Is there a way for me to identify the vertical gaps in my code using JavaScript?

Within this specific HTML document, there are multiple div elements that have an absolute positioning applied to them I am looking to develop a JavaScript code that can determine the row of each individual div. I define a row as any space on the vertical ...

Determination of an arc trajectory using JavaScript

I have been trying to figure out how to replicate this effect. The Red arrowhead remains stationary while the background features a curved path. Currently, I am adjusting the background position to give the illusion of the arrowhead moving along the curved ...

The hyperlink within the dropdown menu in HTML code is malfunctioning

I'm currently working on my personal website using HTML and CSS with textedit. I've successfully created functional links for the main navigation menu headings, but I'm encountering issues with the dropdown options. Whenever I try to click o ...

Animation displayed on page load before running

Is there a way to ensure that my animation runs smoothly without any lag or jankiness, either while the page is loading or immediately after loading? I have attempted to preload the images using a preload tag in the header of my HTML, but unfortunately, t ...

Initiate the printing process by executing the window.print() function. As the document is being

Here's the code snippet : <body> <div class="headerCont noprint"> <div class="headerHold"> <div class="logoCont"><img src="images/logo.jpg" width="104" height="74" alt="Logo"> ...

Customize Your Form Labels with Bootstrap: Changing Label Color in Forms

I am completely new to using bootstrap, particularly bootstrap 3. The goal I have is to change the color of labels such as "Name", "Email Address", "Phone Number" and "Message" from dark grey to white in the design shown below. https://i.sstatic.net/yDTto ...

Using requestAnimationFrame to animate several independent objects

I'm currently working on animating two different objects: a square and a circle. Each object has its own button to initiate the animation, which involves moving the object from left to right. However, I've run into an issue where clicking on one ...

Error: The parent selector "&" cannot be used in top-level selectors. $::webkit-input-placeholder

I am facing an issue while trying to run a legacy create-react-app that utilizes Sass. Initially, when I ran npm start, I encountered the error 'Cannot find module sass', which resembled the message found in this stack overflow post. To resolve t ...

"Error encountered while trying to perform a JavaScript _doPostBack

In my asp.net application, I have an HTML table where each td element has a unique id. When a td element is clicked, I use JavaScript to store the id in a hidden field. After that, I attempt to trigger _doPostBack from JavaScript to utilize the hidden fiel ...

HTML and CSS styled accordion with nested checkboxes: handling long items

I am currently working on creating a multi-level accordion for an aside navigation section on a webpage. However, I have encountered an issue where the background color extends too far when hovering over a specific element. This occurs on a folder-type ite ...

The challenge of navigating CSS specificity guidelines

In my CSS file, I have defined two styles for a table with the class "myTable". The first style sets the background color of header cells to gray, while the second style sets the background color of odd rows to blue: .myTable th { background-color: gr ...

What is the best method for choosing all children's text except for a specific tag in Selenium's XPath selector?

Here is the HTML code I am working with: <div id="content"> <h1>Title 1</h1><br><br> <h2>Sub-Title 1</h2> <br><br> Description 1.<br><br>Description 2. <br><br ...

How can we extract text from a div containing a Mark tag using Selenium WebDriver?

When using Selenium Webdriver, how can I extract the complete text from a div with a Mark tag? I am trying to confirm if the word 'correctly' appears within it. Below is an example of HTML code: <div class="faq-node-body"> blah ...

The Outer Div Can't Contain Google Maps

I am currently working on integrating a map widget into a dashboard I created using gridstack.js. The sample widget layout that I am aiming for can be seen in the link below: https://i.sstatic.net/ZQP6G.png My goal is to embed the map within the inner (w ...

Open Chrome in fullscreen mode directly from your Android home screen without the statusbar displayed

One of my clients is looking to have a specific website launched from an icon on an Android tablet. Since he is leasing the tablets, we have full control over the hardware. The goal is for these tablets to exclusively display his site (which is a slideshow ...

Incorporate text directly into Bootstrap select input on a single line

I am attempting to include an asterisk in a select input field. I can achieve this easily by applying my own CSS, but the challenge is to accomplish this using Bootstrap 3.3.7 or an older version while displaying the asterisk on the same line as shown in t ...

There was an issue retrieving the value from the $.ajax() error function, as it returned [

After successfully receiving data from the input field and sending it to the database, everything seems to be working fine. However, when attempting to retrieve the data after sending it to the database, an error is encountered: [object HTMLInputElement]. ...