Unskewed child not aligning

前端 未结 4 1391
南方客
南方客 2021-02-05 11:41

Note: This question is about a problem with output, and not about creation of any shape.


I recently created a shape :

4条回答
  •  灰色年华
    2021-02-05 12:02

    The behaviour of the "unskewed" child is normal, it is the way skew works. In order to understand this, I am going to simplify the question to :

    why isn't skewX(40deg) the same as skewX(20deg) skewX(20deg)?

    Difference between skewX(40deg) and skewX(20deg) skewX(20deg)

    div {
        width: 100px; height: 100px;
        position:absolute;
        top:20px; left:20px;
        transform-origin: 0 0;
    }
    .d1 {
        transform: skewX(40deg);
        background: red;
        opacity:0.7;
    }
    .d2 {
        transform: skewX(20deg) skewX(20deg);
        background: blue;
        opacity:0.7;
    }
    /** FOR THE DEMO **/
    body {background: url('http://i.stack.imgur.com/GySvQ.png');background-size: 10px;}
    .m {text-align:right;padding-top:105px;}
    .m1{width:83px;color:red;border-right:1px solid red;}
    .m2 {width:72px;color:blue;border-right:1px solid blue;}
    p{margin:0 0 5px 150px;color:red;}
    .b{color:blue;}
    x = 83

    x = 72

    skewX(40deg)

    skewX(20deg) skewX(20deg)

    Note: for the sake of explanation I will be using a 100*100 square div and the transform origin is set on the top left corner of this div. Like in the above code snippet.


    To understand the difference between the two transformations, we need to explore the way the CSS skew() function works. The specs say :

    A 2D skew transformation along the X axis with the parameter alpha is equivalent to the matrix: skewX() matrix

    So this means we can calculate the coordinates of each point of a 2D X skewed element like this :

    | 1 tan(α) | . | x |
    | 0   1    |   | y |
    
    • α is the X skewed angle
    • x/y the coordinates of the point before transformation

    For skewX(40deg)

    α = tan(40deg) ~= 0.83
    
    | 1  0.83 | . | 0   |   | 83  |
    | 0  1    |   | 100 | = | 100 |
    

    The new coordinates are x = 83 as seen in the code snippet example.


    For skewX(20deg) skewX(20deg)

    α = tan(20deg) ~= 0.36
    

    first skew :

    | 1  0.36 | . | 0   |   | 36  |
    | 0  1    |   | 100 | = | 100 |
    

    Second skew :

    | 1  0.36 | . | 36  |   | 72  |
    | 0  1    |   | 100 | = | 100 |
    

    The new coordinates are x = 72 as seen in the code snippet.


    Conclusion

    Both transformations don't give the same result. So skewY(20deg) skewY(-40deg) isn't the same transformation as skewY(-20deg) and the two top corners of the red and green elements can't align as :

    tan(20deg) != tan(40deg)/2 
    

    References :

    • The CSS3 matrix() Transform for the Mathematically Challenged
    • CSS transform skew: math unveiled
    • CSS Transforms Module Level 1

提交回复
热议问题