Calculating the angle needed to rotate the square involves using trigonometry. First, determine the vertical and horizontal distances between the centers of the squares. Then, find the inverse tangent to determine the rotation angle required. Assuming you want the top border to face the blue square.
// Obtain the red and blue squares
var red = $('#red');
var blue = $('#blue');
// Find the x and y coordinates of the centers of the red and blue squares
var redX = red.offset().left + red.width() / 2;
var redY = red.offset().top + red.height() / 2;
var blueX = blue.offset().left + blue.width() / 2;
var blueY = blue.offset().top + blue.height() / 2;
// Calculate the offsets
var X = blueX - redX;
var Y = blueY - redY;
// Adjust the angle by adding an additional 90 degrees so that the top border faces the blue square
var angle = Math.atan2(Y, X) + Math.PI / 2;
// Rotate the red square by modifying its CSS properties
red.css({'-webkit-transform' : 'rotate('+ angle +'rad)',
'-moz-transform' : 'rotate('+ angle +'rad)',
'-ms-transform' : 'rotate('+ angle +'rad)',
'transform' : 'rotate('+ angle +'rad)'});
Shown below is a diagram illustrating the mathematical process:
X
__________B
| /
| / X = B(x) - R(x)
| / Y = B(y) - R(y)
| / tan(A) = Y / X
Y | / A = atan(Y / X)
| /
|__/
|A/
|/
R
I've created a Codepen example demonstrating this concept as well.
Trust this explanation proves beneficial!