Home > Net >  How to return the opposite values of getBoundingClientRect()?
How to return the opposite values of getBoundingClientRect()?

Time:09-22

I have problem with getBoundingClientRect(), everything is fine if i have left: 0; on div but my goal is to make div that starts from right: 0; and ends on left edge of element. What is the best way to do this? expected result

CodePudding user response:

If i understood you correctly you can get the position of the box. Then, to get the distance to the end of the container you can subtract this box position from the total container width.

For example:

  • The overlay width is [container width] - [box left position]
  • The overlay height is [container height] - [box top position]

You can then use these values to place the overlay as you needed it.

I have create a little example where i have a box inside a container. With JS we get the needed values and then we create and place an overlay that goes from the left side of the box until the end of the container.

You could use the same idea for the other overlay (from bottom to top)

// Get dom elements
const container = document.querySelector('.container');
const box = document.querySelector('.box');

// Get width of the container (or maybe the window, whatever you need)
const containerWidth = container.getBoundingClientRect().width;
// Get the left position of the box
const boxLeftPos = box.getBoundingClientRect().left;

// Calculate the width of the overlay
// from the left side of the box until the end of the container
const overlayWidth = containerWidth - boxLeftPos;

// Create an overlay element and page it on the page
const overlayElement = document.createElement('div');
overlayElement.classList.add('overlay');
overlayElement.style.left = `${boxLeftPos}px`;
overlayElement.style.width = `${overlayWidth}px`;
container.append(overlayElement);
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.container {
  background-color: lightgrey;
  height: 100vh;
  width: 100%;
  position: relative;
}

.box {
  height: 40px;
  width: 50px;
  top: 100px;
  left: 40px;
  background-color: purple;
  position: absolute;
}

.overlay {
  background-color: rgb(255 0 0 / 25%);
  position: absolute;
  top: 0;
  height: 100%;
}
<div >
  <div ></div>
</div>

  • Related