Home > Software design >  Transform skew without changing element position
Transform skew without changing element position

Time:12-29

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 >
  <div ></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?

CodePudding user response:

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 >
  <div ></div>
</div>

CodePudding user response:

Skew will transform the div, in this case in the X direction, similar to translate. Here is a test I did using skewed and translate in codepen. And here is what I added:

    .inner {
    width: 50%;
    height: 100%;
    position: absolute;
    transform: skew(30deg) translateX(71.5px);
    background-color: blue;
    opacity: .7;
    }
  • Related