Using CSS3 property transform, elements can be translated, rotated, scaled and skewed in two or three dimensional space. This tutorial will covered translating an element in X and Y direction using CSS transform (2D) translateX and translateY.
CSS Syntax:
transform:translate(10px, 20px); transform:translateX(10px); transform:translateY(20px);
CSS transform – translateX and translateY example
Here box1 will be translated by 10px in X (right) and Y (downward) direction. Note that the translation does not affect the placement on other element in html. Just that the translated element gets shifted.
<style type="text/css"> .outer { width: 100px; height:100px; background-color:lightgray; } .box1 { width: 50px; height:50px; background-color :green; transform: translate(10px, 10px); } .box2 { width: 50px; height:50px; background-color :lightblue; } </style> <div class="outer"> <div class="box1"></div> <div class="box2"></div> </div>
CSS transform – translateY using percentage
Here translation is done using percentage of element size. Note that this can very useful to shift an element by percentage of its size when size is unknown.
<style type="text/css"> .outer { width: 100px; height:100px; background-color:lightgray; } .box1 { width: 50px; height:50px; background-color :green; transform: translate(50%, 50%); } </style> <div class="outer"> <div class="box1"></div> </div>
Specification and Browser compatibility
Specification | Status | Categories |
---|---|---|
CSS3 2D Transforms | W3C Working Draft | CSS3 |
Chrome | Firefox | IE | Edge | Safari | Opera |
---|---|---|---|---|---|
Yes 36+ | Yes 16+ | Yes 10+ | Yes 12+ | Yes 9+ | Yes 12.1+ |
Android Chrome | Android Firefox | iOS Safari | IE Mobile | Opera Mobile |
---|---|---|---|---|
Yes 47+ | Yes 44+ | Yes 9.0-9.2+ | Yes 10+ | Yes 11+ |
source: caniuse.com