Manuel Schweigert Manuel Schweigert - 4 months ago 11
HTML Question

transform: rotate on <img> with negative margin

I try to rotate an image around the bottom right corner and then move it back up to the origin using negative margin.

When I do this, there is always a few pixels of space left to the top that the browser (both IE and Chrome) refuse to move it further. If I assign

position: absolute
to the image, it will get positioned correctly.

Here is a minimal example: https://jsfiddle.net/ny0rm75b/

<div>
<img src="http://placehold.it/600x300">
</div>

<div class="fixed">
<img class="fixed" src="http://placehold.it/600x300">
</div>


css:

div{
width:600px;
height: 300px;
box-sizing: content-box;
border: 5px solid orange;
margin: 15px;
}

img{
transform-origin: 600px 300px;
transform: rotate(180deg);
margin-left: -600px;
margin-top: -300px;

}

div.fixed{
position: relative;
}
img.fixed{
position:absolute;
}


Why does
position: absolute
fix this issue, or rather, what is the cause of this in the first place?

Answer

Images are inlineelements and are subject to text-like considerations. There is usually space under the text baseline to account for descenders on characters.

Setting the image to display:block stops it being inline...as does using position:absolute.

div{
  width:600px;
  height: 300px;
  box-sizing: content-box;
  border: 5px solid orange;
  margin: 15px;
}

img{
  transform-origin: 600px 300px;
  transform: rotate(180deg);
  margin-left: -600px;
  margin-top: -300px;
  display: block;

}
<div>
  <img src="http://placehold.it/600x300">
</div>

That said, there is no real reason to use margins at all (in this instance)...and the block fix isn't necessary with a simple 180 deg rotation.

div {
  width: 600px;
  height: 300px;
  box-sizing: content-box;
  border: 5px solid orange;
  margin: 15px;
}
img {
  transform: rotate(180deg);
}
<div>
  <img src="http://placehold.it/600x300">
</div>