2

I have a div which is absolutely positioned and has a rotation transform of 45deg. It has a fixed height but width can be changed dynamically.

When I increase the width dynamically the whole element drifts right and up.

How do I prevent this movement so that the left edge stays in place?

let box = document.getElementById('box')
let range = document.getElementById('range')

box.style.width = range.value + "px"; 

range.oninput = function() {
    box.style.width = range.value + "px"; 
}
#box {
  height: 100px;
  top: 100px;
  left: 100px;
  position: absolute;
  border: 1px solid black;
  transform: rotate(45deg)
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Resize box</title>
</head>
<body>
<div class="slidecontainer">
  <input type="range" min="50" max="300" value="50" class="slider" id="range">
</div>
  
<div id="box"></div>
</body>
</html>

1 Answer 1

1

Set transform-origin:

let box = document.getElementById('box')
let range = document.getElementById('range')

box.style.width = range.value + "px"; 

range.oninput = function() {
    box.style.width = range.value + "px"; 
}
#box {
  height: 100px;
  top: 100px;
  left: 100px;
  position: absolute;
  border: 1px solid black;
  transform-origin:0 0;
  transform: rotate(45deg)
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Resize box</title>
</head>
<body>
<div class="slidecontainer">
  <input type="range" min="50" max="300" value="50" class="slider" id="range">
</div>
  
<div id="box"></div>
</body>
</html>

Sign up to request clarification or add additional context in comments.

2 Comments

Well, that was easy!!
@spinners, absolutely!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.