Calculation for determining the fill of a DIV's remaining height

Here is what I have:

<div id="modal-container">
  <div id="modal-body"></div>
  <div id="modal-footer"></div>
</div>

I am currently working on a JavaScript function to adjust the height of #modal-body to fill in the remaining available space. This task is proving to be more complex than anticipated:

$('#modal-body').css({
  'height': function() {
    // amount of vertical space available.
    // containerHeight represents the height of the modalView container
    var containerHeight = $('#modal-container').height();
  
    // height taken up by the footer
    var footerOuterHeight = $('#modal-footer').outerHeight();

    // accounting for padding, margins and borders of the div
    var paddingTop = $(this).css('padding-top').replace('px', '');
    var paddingBottom = $(this).css('padding-bottom').replace('px', '');
    var marginTop = $(this).css('margin-top').replace('px', '');
    var marginBottom = $(this).css('margin-bottom').replace('px', '');
    var borderTop = $(this).css('border-top-width').replace('px', '');
    var borderBottom = $(this).css('border-bottom-width').replace('px', '');

    return containerHeight - footerOuterHeight - paddingTop - paddingBottom - marginTop - marginBottom - borderTop - borderBottom;
  }
});

The issue arises from the inability to directly set an "outerHeight" property for #modal-body, requiring us to calculate it by considering its padding, border, margin, etc.

In any case, the above function is mostly effective. Here are my two questions:

  1. Is there a simpler or more efficient way to achieve this?
  2. There seems to be a 1px discrepancy. The presence of a scrollbar in #modal-container suggests this. When deducting an additional 1px, it functions correctly. What might I be overlooking? Are there other factors aside from padding, margin, and border that should be considered?

Answer №1

Is there a more efficient way to accomplish this task?

A better solution does exist.

The issue arises from the inability to set an "outerHeight" attribute for our #modal-body, necessitating the calculation considering its padding, border, margins, etc.

That's not entirely accurate. You can utilize box-sizing: border-box;, which ensures that sizing includes borders and padding, but not margins. Managing margins will still be required, but this approach simplifies the task;

#yourElement {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

Edit: Achieve this using only CSS; no JavaScript necessary. Refer to this demo. Below is the basic HTML layout:

<div class = "container">
    <div class = "fluid">Glee is very very awesome! I have margins, too!</div>
    <div class = "fixed">Glee is awesome!</div>
</div>

CSS:

.container {
    height: 300px; /*adjust as needed*/
    position: relative; /*essential*/
}
.fluid {
    margin: 10px; /*illustrative value*/
    position: absolute;
    top: 0;
    bottom: 75px; /*corresponding to height of bottom fixed-height div*/
    right: 0;
    left: 0;
}
.fixed {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 75px; /*modify as required*/
}

Trust this is beneficial!

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

Troubleshooting: Potential Reasons Why Registering Slash Commands with Options is Not Functioning Properly in Discord.js

While working on a Discord bot, I encountered an issue while trying to register a slash command with options for the ban command. The error message I received was: throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: ...

What is the best way to connect an image to a different webpage?

I have a question regarding a div that contains an image acting as a link to another page. The image has text overlaying it and can be found at this link: This code was sourced from the internet, but I made some modifications to it. My goal is simply to ...

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

Issue with React Hook Form - frequent failure in submitting the form

I have implemented the useForm hook from https://www.npmjs.com/package/react-hook-form. However, I am encountering some inconsistent behavior where it sometimes works immediately, sometimes requires a page refresh to work, and sometimes doesn't work a ...

Interactive quiz program based on object-oriented principles

As I work on developing a quiz app using JavaScript, everything seems to be going well. However, I've encountered an issue with validation where my code is validating the answers twice - once with the correct answer from the previous question and agai ...

Having issues with using the class selector in SVG.select() method of the svg.js library when working with TypeScript

Exploring the capabilities of the svg.js library with typescript has presented some challenges when it comes to utilizing CSS selectors. My goal is to select an SVG element using the select() method with a class selector. In this interactive example, this ...

Issue with NodeJS: The HTTP GET request is returning the code instead of the expected JSON object

My NodeJS code is designed to fetch a JSON object from a website. Here is the snippet: var http = require('http'); var url = { host: 'www.sample-website.com', headers: { "Accept": "application/json", 'Content-Type&apos ...

Displaying random characters in place of Angular 6 font awesome icons

Recently, I started a new project with the angular cli and incorporated font-awesome 4.7.0. After that, I included it as a dependency in my angular.json file. "styles": [ "./node_modules/font-awesome/css/font-awesome.min.css", "./node ...

Ensuring the footer stays anchored at the bottom using Material-UI Expansion Drawers

Utilizing Material-UI@next in my React application, I have a component that showcases a list of items using Expansion Panels. Additionally, there is a straightforward <Footer /> component structured like this: import React, { Component } from "react ...

Limiting the jQuery UI Datepicker to only allow past dates: How to make it happen?

I have implemented a jQuery UI Datepicker that restricts selection to only Sundays. However, I want to further enhance this by preventing users from selecting any dates in the future starting from today. Below is the current code snippet I am using for th ...

What sets apart defining a function in ReactJS using only parentheses versus curly braces within parentheses?

As a newcomer to React, I encountered an interesting application that had functions defined in two different ways. One style was async function (a, b) => {//body}, which I found easy to understand. However, another set of functions followed the struct ...

Storing data in Angular service for future use

My ui-grid is functioning correctly, utilizing server side pagination with a view button to display row details on a separate page. However, upon returning to the grid after viewing details, it defaults back to displaying the first page. I would like it to ...

How to make the dropdown menu in Material UI Select have a horizontal scroll bar?

I've run into an issue in my project with the material ui Select component. The dropdown contents are too long and don't fit properly. To solve this problem, I tried adding a horizontal scroll to the dropdown menu by setting OverflowX property i ...

Getting YQL financial information using jQuery and showing it using the .html() method

Struggling with the .html() function and YQL data pulled issue. Despite data being pulled successfully (as seen in the YQL console), it is not being displayed. Here's the provided code snippet: HTML Section <ul id="TECO-container"> <li ...

Having trouble with Autocomplete Search feature in Laravel?

I have a search field with the same name and id on both my categories page and products page. The autocomplete suggestions are working fine, but when I click on a suggested product in the search field, it stays on the same page instead of redirecting me to ...

Utilize the synchronization feature of ES6 Promises in Jasmine with the then/catch method

I have an angular controller that needs to be tested. This controller utilizes a service to fetch data from a server, and the service returns ES6 Promises. function MyController($scope, MyService) { $scope.doSomething = function () { MyService.foo() ...

An issue arises in Slate.js when attempting to insert a new node within a specified region, triggering an error

A relevant code snippet: <Slate editor={editor} value={value} onChange={value => { setValue(value); const { selection } = editor; // if nothing is currently selected under the cursor if (select ...

Struggling to align Jssor slider perfectly within a Bootstrap container

Struggling to center my slider images while using bootstrap with jssor. Despite trying to zero out the margins in the code below, the images within the slider remain aligned to the left side of the container. Any suggestions on how I can properly center ...

Tips for extracting variables from a querystring in Express?

I am trying to retrieve values sent to the server: "/stuff?a=a&b=b&c=c" Can you please advise me on how to extract these values using express? So far, I have attempted... app.get( "/stuff?:a&:b&:c", function( req, res ){}); ...but unfo ...

Struggling to generate an HTML table using JSON data

Struggling with generating an HTML table from JSON data, I'm inexperienced and having trouble with the logic. The JSON data I have needs to populate a complex dynamic HTML table. The design of the table is intricate, making it challenging for me to i ...