javascript – Reverse an image with CSS while maintaining the same position

Question:

Here is a sample code: https://codepen.io/yury-leonov/pen/rZxxQE

$(".example").on("click", function(e){
  $(e.target).toggleClass("reverse");
})
.reverse{
    transform: scaleX(-1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div style="width: 700px;height: 700px;margin-left: 100px">
    <svg viewBox="-200 0 700 700">
        <image class="example" href="https://i.pinimg.com/originals/6f/3d/6a/6f3d6aab605e25af947d804c4a2cb558.jpg" width="150px" height="150px" x="50", y="50"/>
        <image class="example" href="https://i.pinimg.com/originals/6f/3d/6a/6f3d6aab605e25af947d804c4a2cb558.jpg" width="150px" height="100px" x="100", y="0"/>
      <!--x value can be changed during time-->
    </svg>
</div>

Problem:

When rotated, the arrow moves from its position.

Expected:

The arrow should remain there. Needs to be done based on css (no js calculating the final x value)

PS:

Using translateX (- ??? px) is not an option because there can be many objects that need to be rotated.

Free translation of the SVG question . Reverse image using css. Keep image at the same place by @Yuriy Leonov .

Answer:

Use transform-origin and transform-box

$(".example").on("click", function(e){
  $(e.target).toggleClass("reverse");
})
.reverse{
    transform: scaleX(-1);
    transform-origin: center;
    transform-box: fill-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div style="width: 700px;height: 700px;margin-left: 100px">
    <svg viewBox="-200 0 700 700">
        <image class="example" href="https://i.pinimg.com/originals/6f/3d/6a/6f3d6aab605e25af947d804c4a2cb558.jpg" width="150px" height="150px" x="50", y="50"/>
        <image class="example" href="https://i.pinimg.com/originals/6f/3d/6a/6f3d6aab605e25af947d804c4a2cb558.jpg" width="150px" height="100px" x="100", y="0"/>
      <!--x value can be changed during time-->
    </svg>
</div>

Free translation of SVG answer . Reverse image using css. Keep image at the same place by @Robert Longson .

Scroll to Top