Margin to apply to position div after skewing with CSS transform

[亡魂溺海] 提交于 2019-12-01 08:29:53

No need math, simply adjust transform-origin:

.parent {
  border: 1px solid red;
  position: relative;
  margin-top: 100px;
  height: 200px;
}

.child {
  border: 1px solid blue;
  position: absolute;
  width: 100%;
  height: 100%;
  transform: skewY(-3.5deg);
  transform-origin:top right;
}
<div class="parent">
  <div class="child">
    content
  </div>
</div>

But if you want to play with math the exact formula is :

top = tan(Xdeg)*(width/2)

green is the top, purple is half the width and yellow is the angle of skew

In this case we have -3.5deg so the tan(-3.5deg) = -0.061 so top = -0.061 * 50% of width BUT since the reference of the div is top left when applying top property we need to consider a minus sign because we want to adjust the top right corner and not the top left one

.parent {
  border: 1px solid red;
  position: relative;
  display:inline-block;
  height: 100px;
  width:var(--w); /*Used fixed width to make calculation easy*/
}

.child {
  border: 1px solid blue;
  position: absolute;
  width: 100%;
  height: 100%;
  transform: skewY(-3.5deg);
  top:calc(0.061 * (var(--w) / 2));
}
<div class="parent" style="--w:200px;">
  <div class="child">
    content
  </div>
</div>
<div class="parent" style="--w:100px;">
  <div class="child">
    content
  </div>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!