Home  >  Q&A  >  body text

How to apply multiple transforms in CSS?

<p>How do I apply multiple <code>transform</code> using CSS? </p> <p>Example: The following only applies translation, not rotation. </p> <pre class="brush:php;toolbar:false;">li:nth-child(2) { transform: rotate(15deg); transform: translate(-20px,0px); }</pre> <p><br /></p>
P粉066224086P粉066224086439 days ago642

reply all(3)I'll reply

  • P粉081360775

    P粉0813607752023-09-01 12:18:08

    I'm adding this answer not because it might be helpful, but because it's true.

    In addition to using the existing answers explaining how to do multiple translations via links, you can build the 4x4 matrix yourself

    I showed the rotation matrix from some random site I found while googling:

    Rotate around the x-axis:

    Rotate around y-axis:
    Rotate around z-axis:

    I couldn't find a good translation example, so assuming I remember/understand it correctly, the translation:

    [1 0 0 0]
    [0 1 0 0]
    [0 0 1 0]
    [x y z 1]

    See the

    Wikipedia article on transformations and the Pragamatic CSS3 tutorial explains this very well. Another guide I found that explains arbitrary rotation matrices is Egon Rath's Notes on Matrices

    Of course, matrix multiplication is possible between these 4x4 matrices, so to perform rotations and translations you need to create the appropriate rotation matrix and multiply it by the translation matrix.

    This gives you more freedom to get it just right, and also makes it almost completely impossible for anyone to understand what it's doing, including you for five minutes.

    But, you know, it works.

    Edit: I just realized that I missed probably the most important and practical use, which is to step-by-step create complex 3D transformations via JavaScript, where things would make a lot more sense.

    reply
    0
  • P粉231112437

    P粉2311124372023-09-01 09:44:56

    You have to put them on one line like this:

    li:nth-child(2) {
        transform: rotate(15deg) translate(-20px,0px);
    }

    When you have multiple transformation directives, only the last one is applied. Just like any other CSS rule.


    Remember that multiple transformations in one line are applied from right to left.

    This:Transformation: scale(1,1.5)rotate(90deg);
    And: Transformation: Rotation (90deg) Scale (1,1.5);

    Replacing will not produce the same result:

    .orderOne, .orderTwo {
      font-family: sans-serif;
      font-size: 22px;
      color: #000;
      display: inline-block;
    }
    
    .orderOne {
      transform: scale(1, 1.5) rotate(90deg);
    }
    
    .orderTwo {
      transform: rotate(90deg) scale(1, 1.5);
    }
    <div class="orderOne">
      A
    </div>
    
    <div class="orderTwo">
      A
    </div>

    reply
    0
  • Cancelreply