How do I set an element's CSS right and bottom properties according to the element's DOMRect?

Viewed 27

I am trying to write a custom element that is resizable (I have done this before, but it was very messy).

In CSS, the properties right and bottom are measured in some unit from their referents, i.e. right is measured from the right side of the viewport, instead of the left like in the DOMRect, which you can get from an element with the method getBoundingClientRect.

I much prefer the DOMRect, but apparently the DOMRect is not live, i.e. you can't change the element with it.

Is it possible to set the properties right and bottom in CSS based on the top-left corner of the viewport, or is there a way to connect a DOMRect to an element, so that what I do to it, I also do to the element?

Thanks in advance.

Edit: I am creating a window module, like in an operating system. The problem with the CSS properties is that if I change the left property in CSS, element.style.left, that is, the width property doesn't change with it, naturally. And the right property is not based on the top-left corner, like in a DOMRect.

Is there any way to treat my element like a DOMRect, or is there a property in CSS that could help me?

2 Answers

You can do this now using CSS using the resize property and it is widely supported. You need to ensure that you set overflow to something other than visible which is the default.

For example:

div {
  width: 100px;
  height: 100px;
  background: blue;
  resize: both;
  overflow: hidden;
}

Here is a working demo; apologies if you really want to do this with JS but if it's solely for resizing and you don't need custom thumbs for dragging/etc then this will do the trick and also be super performant.

I wrote a method to get a CSS friendly size. Problem solved.

getCssFriendlySize(side, magnitude) {
  let size
  switch (side) {
    case 'top':
      size = magnitude
      break
    case 'left':
      size = magnitude
      break
    case 'bottom':
      size = window.innerHeight - magnitude
      break
    case 'right':
      size = window.innerWidth - magnitude
  }
  
  return size
}
Related