Ensuring the child div's height does not overflow beyond the parent div

When dealing with a parent div and a child div, both having different heights, how can I specifically retrieve the height of the portion of the child div that is within the boundaries of the parent div? Using

document.getElementById("id").style.height
provides the entire height of the child div. Any insights on this would be greatly appreciated. Thank you for your help in advance!

I apologize if my terminology may not have been technically accurate.

Answer №1

It seems like you're interested in calculating the remaining height within a parent element based on the positions of its child elements:

To do this, you can use the following formula:

let parent = document.getElementById("parent")
let child = document.getElementById("child")
console.log(parent.getBoundingClientRect().bottom - child.getBoundingClientRect().top)
#parent{
  height: 300px;
  background-color: grey;
}
.some-element{
  height: 5px;
}
#child{
  background-color: orange;
  height: 500px;
}
<div class="some-element"></div>
<div id="parent">
  <div class="some-element"></div>
  <div id="child">Child</div><!-- 300 - 5 = 295px inside the parent-->
  <div class="some-element"></div>
</div>
<div class="some-element"></div>

Answer №2

Method 1:

You have the option of using .parentNode to retrieve the parent element (if direct access is not available), and then obtaining the height of the parent. It should be equal to the portion of the child div that remains within the parent div, as illustrated below:

document.getElementById("#id).parentNode.style.height

Method 2: (even effective if the child div has been repositioned)

If accessing the parent element is not an issue, you can achieve a more precise solution by acquiring the coordinates of both the parent and child elements. With a bit of mathematical calculation, you can pinpoint the exact section where the child div intersects with the parent div...

let parentCoord = document.getElementById('parentId').getBoundingClientRect();
let childCoord = document.getElementById('childId').getBoundingClientRect();
var left = Math.max(parentCoord.left, childCoord.left);
var right = Math.min(parentCoord.right, childCoord.right);
var top = Math.max(parentCoord.top, childCoord.top);
var bottom = Math.min(parentCoord.bottom, childCoord.bottom);

Now, you possess the precise coordinates of the area where the child div overlaps with the parent div. If you require the width, a straightforward calculation can be performed:

var width = right - left;
var height = bottom - top;

If this solution aligns with your needs, feel free to implement it. In case further clarification or assistance is required, do provide additional details about your objective... Otherwise, happy coding!

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 overflow of CSS text selection color spills beyond the boundaries of the box

I'm just starting to learn CSS and was wondering if there is a way to prevent the text selection color from extending into the 'gutter' (I believe that's the correct term) like shown here: It may seem trivial, but I've observed th ...

Retrieving the chosen value when there is a change in the select tag

Building a shop and almost done, but struggling with allowing customers to change product quantities in the cart and update prices dynamically. I've created a select-tag with 10 options for choosing quantities. I'd like users to be able to click ...

Is there a way to automatically hide divs with the style "visibility:hidden" if they are not visible within the viewport?

Currently, I am working on developing a mobile web app. Unfortunately, Safari in iOS 5.1 or earlier has limited memory capabilities. In order to reduce memory usage while using css3 transitions, I have discovered that utilizing the css styles "display:none ...

Repeating every other item in a list using ng-repeat in AngularJS

Using AngularJS version 1.5.3 In my view, I have a list of items that I want to display. After every two items, I would like to show a new div below the first one. <div class="col text-center" ng-repeat="event in weekDay.events"> &nbsp;& ...

Difficulty closing Modal Popup when multiple Modals are displayed simultaneously

I am facing a challenge with transitioning between modal screens When the button on the screen is clicked, Modal1 opens: $modal.open({ templateUrl: 'abc.html', controller: 'abcCtrl', size: 'lg', scope: $scope ...

Utilizing interactions between a JavaScript scrollable container and Python/selenium

My goal is to utilize Selenium/Python in order to automate the process of downloading datasets from . While I am new to Javascript, I am determined to learn and overcome any obstacles that may arise during this project. Currently, I am focusing on the init ...

CSRF fails to execute during the initial post submission

This is my first time dealing with CSRF and reaching out to Stack Overflow for the first time. After struggling through the configuration, I finally managed to get it working almost perfectly. However, I ran into an issue where if I open a bookmarked page ...

Managing State in a React Drawer Interface

One day, I decided to create a page with a Sidebar on the left, an Appbar at the top, and a content area. Initially, everything functioned seamlessly as one enormous component. However, as we all know, React's charm lies in breaking down various eleme ...

I would like to mention a website without inserting a direct hyperlink, for example, in the Safari browser

Is there a way to prevent a website name from becoming a clickable link in Safari? In my marketing email, I am highlighting the websites of both my client and their competitor. When mentioning the competitor's site "sitename.com," I want to avoid cre ...

Gulp fails to generate a CSS file after compiling Sass to CSS

Recently, I've been having trouble compiling my sass file to css. Even though it was working fine before and I haven't made any changes, now my CSS file is empty. Below is the task I am trying to accomplish: gulp.task('sass', function ...

Tips on utilizing commas as text input within an HTML input array

Is there a way to pass a comma in an input field to the server using input arrays? The server currently receives comma-separated input values from an array of inputs, which causes it to consider any commas within the input as separators. For example: HTM ...

What is the best way to assign multiple event handlers to Solid.js components within a single HTML element?

Introduction I am currently exploring Solid.js and facing a challenge in adding multiple event handlers to the same HTML element from different components using JSX. While it's straightforward in Vue, I have noticed that Solid.js overrides events bas ...

Guide to making an object with a value sourced from the redux store

I am looking to develop an object with custom getters and a key representing language. Depending on the language key, different values should be returned by the getters. This is specifically for a customizable language selection feature. As an example, one ...

Navigating through the fetch API request when using express js

I'm looking to use the fetch API to send requests and have those requests handled by Express JS. In my setup, I've put together server.js (Express JS), index.html (home page), and signin.html (sign-in page). index.html <!DOCTYPE html> < ...

Is the background color not being implemented?

I'm struggling with an issue - I can't seem to apply a background color to my top bar. I've tried multiple times but it's still not working. Could you please help me fix this error? Below is the code for my simple top bar: topbar.htm ...

using CSS to position elements that are generated dynamically

Hey there, I'm facing a little issue with my elements. These elements are being generated dynamically and I'd like to display them in a 4 column layout. The challenge is that they arrive separately and I can't simply wrap them in a div and u ...

"Utilizing the Ajax ScriptManager for Effective Namespace Management

After incorporating my Ajax webservice into a namespace (MyCompany.Web.MyService), I encountered an issue where the proxy in Javascript is being regenerated as MyCompany.Web.MyService. Is it possible to change the name of the Javascript proxy to just MySe ...

When processing a response from the backend (using express js), cookies are not being received in the browser while on localhost

I'm currently facing some difficulties with implementing authorization cookies within my application. Whenever I attempt to send a GET request to my API (which is hosted on port 8080) from my React frontend (running on port 3000), the cookies that I ...

Tips for Maintaining Table Headers in Place While Scrolling Through a Table

Check out my jsfiddle: http://jsfiddle.net/7vv9e/2/ In the fiddle, click on the "Add Question" button multiple times until a scroll bar appears next to the table. I am looking to keep the header fixed while scrolling. How can this be achieved? Below is ...

What is the best way to dynamically change className in React.js?

I am working on a Collection component where I need to change the classNames of both the Collection component and its first sibling component when a div is clicked. Even though I tried using UseState, I could only manage to change the className of the cur ...