doniyor
doniyor

Reputation: 37866

rotated image is going out of parent div

I want to rotate the image, but it is going out of parent div.

<div>
  <img src="https://cdn.eso.org/images/thumb300y/eso1907a.jpg">
  <button class="rotate-button">rotate image</button>
</div>

jquery code

$('.rotate-button').on('click', function() {
  var image = $(this).prev('img');
  image.className = "rotated_90deg";
});

unrotated state:

enter image description here

rotated state: enter image description here

how can I keep the image smaller in rotated state, so that it does not go out of parent div?

Upvotes: 2

Views: 1310

Answers (3)

LaZza
LaZza

Reputation: 438

Put the image inside a container div, give it an id or class and set the overflow to hidden:

.imgContainer{
  overflow: hidden;
}

Or if you want the picture to scale so it fits within the div, set max width and height:

.imgContainer img{
  max-width: 100%;
  max-height: 100%;
}

Upvotes: 1

jt3k
jt3k

Reputation: 700

"tranform rotate" does just that. It retains its original height, and the forging is done in a separate visual layer.

the best thing you can do is set the height of the area where the image rotates equal to the largest side of the image

const img = document.querySelector('img');
const {offsetHeight, offsetWidth} = img;
if(offsetWidth >= offsetHeight) {
  img.parentElement.style.height = offsetWidth + 'px';
}


const rotations = [];
const rotateImage = () => {
  rotations.push('rotate(45deg)');
  img.style.transform = rotations.join(' ');
}
div { display: flex; }
img { transition: .3s; margin: auto; }
button { display: block;  margin: auto; position: relative }
<div>
  <img src="http://placekitten.com/300/200">
</div>
<button onclick=rotateImage()>Rotate</button>

hmm ... maybe I hastened to answer. As a solution, "position: relative;" on the button

Upvotes: 2

Shiladitya
Shiladitya

Reputation: 12181

Try using the solution with scale property

$('.rotate-button').on('click', function() {
  var image = $(this).prev('img');
  image.className = "rotated_90deg";
});
.rotated_90deg {
  transform: rotate(90deg) scale(0.5, 1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <img src="https://cdn.eso.org/images/thumb300y/eso1907a.jpg">
  <button class="rotate-button">rotate image</button>
</div>

Upvotes: 3

Related Questions