It's important to note that the transform
property can have varied values, and they are not commutative. For instance, check out these examples:
transform: translateX(100px) rotate(90deg); /* Outcome differs from... */
transform: rotate(90deg) translateX(100px); /* ... this result! */
.box {
height: 100px;
width: 100px;
background: red;
}
#box1 {
transform: translateX(100px) rotate(90deg);
}
#box2 {
transform: rotate(90deg) translateX(100px);
}
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
One might assume that adding a rotation of 45deg
would be
transform: translateX(100px) rotate(135deg); /* Accepted modification */
transform: rotate(135deg) translateX(100px); /* Not recommended option! */
.box {
height: 100px;
width: 100px;
background: red;
}
#box1 {
transform: translateX(100px) rotate(135deg);
}
#box2 {
transform: rotate(135deg) translateX(100px);
}
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
However, this approach only works for the initial example, where rotate
was the final transformation function. Typically, the correct sequence should be
transform: translateX(100px) rotate(90deg) rotate(45deg); /* Right way to do it */
transform: rotate(90deg) translateX(100px) rotate(45deg); /* Correct order as well */
.box {
height: 100px;
width: 100px;
background: red;
}
#box1 {
transform: translateX(100px) rotate(90deg) rotate(45deg);
}
#box2 {
transform: rotate(90deg) translateX(100px) rotate(45deg);
}
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
You can also apply this custom method:
$.fn.addTransform = function(val) {
return this.each(function() {
var tr = $(this).css('transform');
if(tr === 'none') tr = '';
$(this).css('transform', tr + ' ' + val);
});
};
Utilize it like so
$('#move').addTransform('rotate(5deg)');
$.fn.addTransform = function(val) {
return this.each(function() {
var tr = $(this).css('transform');
if(tr === 'none') tr = '';
$(this).css('transform', tr + ' ' + val);
});
};
$('input').click(function() {
$('#move').css({
backgroundColor: 'aqua',
position: 'absolute',
transition: '500ms ease-in-out',
right: '-=50px'
}).addTransform('rotate(5deg)');
});
#move {
height: 70px;
width: 70px;
border: 2px solid black;
border-radius: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Move Right" />
<div id="move"></div>