transform

The transform property in CSS allows you to manipulate the position, size, rotation, skewing, and perspective of an element. It’s a versatile tool for creating dynamic and visually appealing effects.

Basic Transformations

  • Translate: Moves an element along the x-axis (horizontally) and/or y-axis (vertically).
    • transform: translate(x, y);
    • Example: transform: translate(100px, 50px); (moves 100 pixels to the right and 50 pixels down)
  • Scale: Enlarges or shrinks an element.
    • transform: scale(x, y);
    • Example: transform: scale(2); (doubles the size in both directions)
  • Rotate: Rotates an element around the z-axis (out of the screen).
    • transform: rotate(angle);
    • Example: transform: rotate(45deg); (rotates 45 degrees clockwise)
  • Skew: Tilts an element along the x-axis and/or y-axis.
    • transform: skew(x, y);
    • Example: transform: skewX(20deg); (skews 20 degrees along the x-axis)

Combining Transformations

  • You can combine multiple transformations within a single transform property by separating them with spaces.
  • Example: transform: translate(100px, 50px) scale(2) rotate(45deg);

Additional Considerations

  • Transform-origin: Specifies the point around which transformations occur.
    • transform-origin: x y;
    • Example: transform-origin: top left; (rotations and scaling occur from the top-left corner)
  • Perspective: Creates a 3D effect by simulating depth.
    • perspective: distance;
    • Example: perspective: 500px; (sets a perspective distance of 500 pixels)
  • Animation: Combine transform with CSS animations to create dynamic effects over time.

Example

.element {
  width: 100px;
  height: 100px;
  background-color: blue;
  transform: translate(100px, 50px) scale(2) rotate(45deg);
  transform-origin: top left;
  animation: rotate 2s infinite linear;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

This code creates a blue square that is translated 100 pixels right and 50 pixels down, scaled to twice its size, rotated 45 degrees, and continuously rotates 360 degrees over 2 seconds.