Search code examples
htmlcsspositioncss-transformsskew

Transform skew without changing element position


I have created the following markup (an example to demonstrate) with a CSS skew transform:

.wrapper {
  height: 100px;
  width: 200px;
  position: relative;
  background-color: orange;
}
.inner {
  width: 50%;
  height: 100%;
  position: absolute;
  top: 0;
  right: 0;
  transform: skew(30deg);
  background-color: blue;
  opacity: .7;
}
<div class="wrapper">
  <div class="inner"></div>
</div>

The problem is that the inner div .inner is being position outside of the container .wrapper even though I set right to 0 because the inner div is skewed 30 degrees. How can I position the inner div with the right most part being at the same position? I could hard code the value of right, but it would appear differently with different screen sizes. If I set the overflow of the outer div to hidden, the right side would still be misaligned. I've seen this post which suggests using transform-origin and -webkit-transform-origin, which I set to right, but none of the solutions worked. What can I do?


Solution

  • You need transform-origin: bottom

    .wrapper {
      height: 100px;
      width: 200px;
      position: relative;
      background-color: orange;
    }
    .inner {
      width: 50%;
      height: 100%;
      position: absolute;
      top: 0;
      right: 0;
      transform: skew(30deg);
      transform-origin: bottom;
      background-color: blue;
      opacity: .7;
    }
    <div class="wrapper">
      <div class="inner"></div>
    </div>