Perfectly Rotate and Mask Thumbnails With CSS3

Perfectly Rotate and Mask Thumbnails With CSS3

Tutorial Details
  • Program: Text editor (I use Coda)
  • Difficulty: Beginner > Intermediate
  • Estimated Completion Time: 45 mins

Ever seen a website showcasing image thumbnails that are slightly rotated? It’s a simple effect that adds a layer of visual personality. Saying that, if you’re not achieving the rotation effect with CSS, you’re working too hard! Learn how to do it right!

Republished Tutorial

Every few weeks, we revisit some of our reader's favorite posts from throughout the history of the site. This tutorial was first published in August of 2011.


Introduction

Image galleries with rotated thumbnails are somewhat infrequent, but it’s a simple trick to add style to your webpage. However, if not done right, achieving and maintaining this effect can sometimes prove to be a major hassle!

To properly achieve this effect, your first thoughts might turn to creating rotated thumbnails in Photoshop. However, this can prove to be difficult in the long term. Disadvantages to creating rotated thumbnails in this way include:

  • Angle Consistency: If the images are not all rotated at the same angle, the visual consistency of page is lost. This means maintaing a PSD of each individual thumbnail properly rotated at a consistent angle. You may, for example, open your PSD and realize you have forgotten the rotation angle of your thumbnails.
  • CMS Thumbnail Generation:If you are running a CMS (such as WordPress), your thumbnails are probably being generated automatically. Using the PSD method described above, you’ll have to manually create and upload each individual thumbnail in your CMS. Also, if you already have an existing site but want to apply the rotation effect to your thumbnails, you’ll have to recreate all thumbnails in Photoshop then re-upload all of them!
  • Long-Term Manageability: Say you’ve created all your thumbnails slightly rotated, but now you want to realign or redesign your gallery. This means you’ll have to regenerate all of your thumbnails. If you’ve been managing your thumbnails in Photoshop, this means you have to adjust and re-save each individual thumbnail all over again. Ugh.

Wouldn’t it be nice if you could perform this little rotation with one line of code? Well you can! Let’s learn how.


Step 1: Understanding Our Goal

A brief overview of what we are trying to accomplish reveals the following steps:

  1. Create an image thumbnail in Photoshop (not rotated)
  2. Insert the thumbnail using the img tag
  3. Mask it appropriately using CSS (think Photoshop masks)
  4. Rotate the thumbnail within the mask using CSS3
Example of image thumbnail and mask

To make sure our gallery degrades gracefully, steps 1-3 will be accomplished using CSS. Step 4 (the rotation effect) will be accomplished using CSS3.


Step 2: Understanding Thumbnail Size and Rotation Angle Increases

Before creating our thumbnails, we need to determine how large each thumbnail will appear on screen.

If our thumbnails are too small and we rotate them at too much of an angle, some of the corners will give us an empty space. Like this:

Empyt space in the mask corners

Hence, to properly fill the mask area, we can conclude that the more our thumbnail is rotated the larger it will have to be. In mathematical terms, as the rotation angle of the thumbnail increases, so too must the thumbnail’s size (and vice versa).

Increase in rotation means an increase in size
Remember this key: the image thumbnail will always be larger than the image mask (thumbnail size > mask size)

A Warning to Those Repelled by Math

Steps 3-6 describe how to mathematically calculate proportionate sizing for the image mask and thumbnail. Understanding it is not necessary to being able to rotate images with the CSS transform property. Rather, its purpose is to help you understand how to properly determine the sizing of your elements to allow full 360° rotation. This ensures you won’t be left with ugly empty corners.


Step 3: Proportionately Equal

To avoid showing empty space in our mask, we must determine ONE of the following:

  • Size of the actual thumbnail
  • Size of the image mask (viewable portion of the thumbnail)

Because the thumbnail and image mask are proportionately equal in size, if we set the size of one we can calculate the size of the other.


Step 4: Determining Dimensions

In this example, we are going to set our image mask size first. By setting the size of our image mask we can use a little math to calculate the thumbnail’s size:

  • Determine the size of the image mask: 180×240 pixels
  • Find the length of the diagonal side
    • Use the Pythagorean theorem ( a2 + b2 = c2 )
      • Our first side (a) is 180px
      • Our second side (b) is 240px
      • So, 1802 + 2402 = c2 (diagonal length)
      • 90,000 = c2
      • 300 = c (take the square root of each side)
    • Our diagonal length (c) equals 300
pythagorean theorem

The diagonal length is an important number. To allow the our thumbnail full 360° rotation, its shortest side must equal the image mask’s longest side. (Even though you may not need it, provisioning for 360° rotation will allow future changes to your rotation angle without having to resize your thumbnails).

Thumbnails shortest side equals masks's longest side

Step 5: Calculating Thumbnail Dimensions

As you can see, our thumbnail’s shortest side must be equal to our mask’s longest side. If it’s not, we’ll be left with empty space. Remember: the thumbnail’s size is proportionately greater than the image mask’s size.

Proportional relationship between thumbnail and mask

Calculating the thumbnail’s size so it properly fits is easy once we know the dimensions of the image mask. We simply take the mask’s largest side (the diagonal) and let it equal the shortest side of our thumbnail.

  • Mask’s largest side (300) equals thumbnail’s shortest side (x)
  • Use the proportionate relationships to find the thumbnail’s length
    • 180 : 300 (mask’s height : thumbnail’s height)
    • 240 : y (mask’s length : thumbnail’s length)
  • Cross multiply to solve
    • 180y = 72,000
  • y = 400 (thumbnail’s length)
Finding y2

We have now determined our mask and thumbnail sizes. We know if our image mask is 180x240px, than the image thumbnail inside that mask must be 300x400px to allow for 360° rotation.

A Happy Note: Because the image mask and thumbnail sizes are proportionately equal, this math would also work if we set our thumbnail size first! We would use the same Pythagorean theorem and proportional relationships to determine the proper sizes.


Step 6: Finally Some HTML

Now that we know all our sizes, let’s build our rotated thumbnails by starting with some basic HTML.

<!DOCTYPE html>
<html>
	<head>
		<title>Rotated Thumbnails with CSS3</title>
		<link rel="stylesheet" href="styles.css" />
	</head>
<body>
<div id="wrapper">
	<h1>Rotated Thumbnails with CSS3</h1>
	<label>Transform Angle: </label>
	<input id="rotation_amount" value="15" />
	<button>Update</button>
	<span id="error_message"> Number values only</span>
	<br />
	<a href="1.jpg" class="mask"><img src="1.jpg" /></a>
	<a href="2.jpg" class="mask"><img src="2.jpg" /></a>
	<a href="3.jpg" class="mask"><img src="3.jpg" /></a>
	<a href="4.jpg" class="mask"><img src="4.jpg" /></a>
	<a href="5.jpg" class="mask"><img src="5.jpg" /></a>
	<a href="6.jpg" class="mask"><img src="6.jpg" /></a>
	<a href="7.jpg" class="mask"><img src="7.jpg" /></a>
	<a href="8.jpg" class="mask"><img src="8.jpg" /></a>
	<a href="9.jpg" class="mask"><img src="9.jpg" /></a>
	<div style="clear:both;"></div>
</div> <!-- #/wrapper -->
</body>
</html>

This basic HTML markup inserts the following:

  • <input> – This will allow the user to change the rotation angle. Also, we set our value attribute to equal the same amount we will initially set in our CSS (15 in this case).
  • <span> – This error message will be hidden from view. Using jQuery, we will show it if the user enters something besides a number in the input box.
  • <img> – These are our thumbnails which can be linked to whatever you please.
  • clear:both – Clears our floated thumbnails
  • class="mask" – The class for our image mask
basic HTML layout

Step 7: CSS Basic Page Styling

Let’s apply some basic styling to our page to give it structure and simplicity.

body {
	margin:0;
	padding:0;
	background:#eee;
	font-family:Geneva, Lucida Sans, Lucida Grande, Lucida Sans Unicode, Verdana, sans-serif;
}
#wrapper {
	width:840px;
	margin:0 auto;
	background:#fff;
	border:1px solid #ccc;
	padding:25px;
	border-top:none;
}
#error_message {
	color:red;
	display:none;
	font-size:.8em;
}

Note here that we hid our error_message by default as we will toggle it’s visibility later on in jQuery.

Add Some CSS3 Effects

Let’s add a few more details to enhance our basic styling

#wrapper {
	border-radius:0 0 5px 5px;
	-moz-border-radius:0 0 5px 5px;
	-webkit-border-radius: 0 0 5px 5px;
	box-shadow:0 0 5px #ccc;
	-moz-box-shadow:0 0 5px #ccc;
	-webkit-box-shadow:0 0 5px #ccc;
}
basic CSS styling

Now we have our content centered with good spacing and some CSS3 effects for enhanced page styling.


Step 8: CSS Styling Image Mask

Let’s apply the image mask to our thumbnails. In our HTML, we wrapped each thumbnail in an anchor tag and gave it a class of mask which we will use in our CSS.

.mask {
	position:relative;
	height:180px;
	width:240px;
	float:left;
	overflow:hidden;
	margin:15px;
	border:5px solid #f6f6f6;
	box-shadow:0 0 1px #000;
	-moz-box-shadow:0 0 1px #000;
	-webkit-box-shadow:0 0 1px #000;
}

Here’s a description of the CSS properties we used (and why we used them):

  • position:relative – Our img tags will be positioned absolutely inside our image mask
  • height, width – Earlier we determined our image mask’s dimensions. This is where we place those sizes.
  • float:left – Floats our images so they appear in a gallery form.
  • overflow:hidden – As calculated earlier, our thumbnails will be 300x400px. However, we will only show a portion (180x240px) of them. This property acts as mask, hiding the portion of our thumbnails that extends outside the 180×240 dimensions.
  • margin – Space out our images
  • border, box-shadow – This gives us a double border (in supporting browsers). The border property gives us a thick, off-white border around the image while the box-shadow gives us a thin, black border around our thick, off-white border.
thumbnails not rotated

Step 9: CSS Sizing The Thumbnails

Set our thumbnail sizes according to the dimensions we calculated in Step 5.

.mask img {
	height:300px;
	width:400px;
}

Step 10: CSS Centering The Thumbnails

Right now, our thumbnails are positioned relatively (from the top left corner).

thumbnail positioned in the top left

We want our thumbnail to be centered horizontally and vertically within the mask.

thumbnail positioned in the center

To accomplish this, we use the following CSS rules:

.mask img {
	position:absolute;
	margin-top:-150px; /* half the height */
	margin-left:-200px; /* half the width */
	top:50%;
	left:50%;
}

Here’s a description of what we did:

  • position:absolute – This positions the thumbnail absolutely within the image mask
  • margin – We set negative margins that are exactly half the height and width of the image (300×400) then set our positioning properties top and left which pull the elements back into perfect center.
thumbnails centered positioning

Step 11: CSS Thumbnail Rotation

We will be using the CSS3 property transform to rotate our elements. So, our CSS will include all the browser prefixes

.mask img {
	-webkit-transform: rotate(15deg);
	-moz-transform:rotate(15deg);
	-o-transform:rotate(15deg);
	-ms-transform:rotate(15deg);
	transform:rotate(15deg);
}

The CSS here is pretty simple. We just place our angle of rotation in parenthesis followed by “deg”.

In this example we used 15 as the rotation value, but you could put a different value there. Because we calculated the sizes of our mask and thumbnail properly, we have provisioned room for full 360° rotation! A positive integer rotates the image to the right, a negative integer rotates the image to the left.

thumbnails rotated

Step 12: CSS Image Hover Effect

As an additional effect, we’re going to add a simple line of CSS that changes our border color when the user hovers over and image.

.mask:hover {border-color:#ddd;}

Step 13: jQuery Changing Rotation Value Dynamically

As a little bonus, we are going to allow the user to enter a value in our input box that changes the CSS rotation angle. So first, let’s add jQuery at the end of our page right before the closing body tag along with a link to our custom script:

<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="js.js"></script>

Step 14: jQuery Document Ready

Now let’s setup jQuery for when the document is ready:

jQuery(document).ready(function($) {
	// code here
});

Step 15: jQuery Initial Function

We create a function for anytime our “update” button gets clicked.

$('button').click(function() {
	//code here
});

Step 16: jQuery Storing Current Rotation Value

We want to store the CSS numeric value for the current angle of rotation in a variable.

var rotation_angle_value = $('#rotation_amount').val();

This code finds the rotation_amount id (which we assigned to the input) and gets its current value. If you remember, we set the initial value attribute to equal 15 (the same as in our CSS code for the rotation angle).


Step 17: jQuery Using isNaN() Function

We want to make the user’s input value our new angle of rotation. However, we want to make sure the user doesn’t accidentally enter a non-numeric value. That’s where the isNaN() javascript function comes in. isNaN() stands for “is not a number”. This function does exactly what its names implies: it checks to see if the value you pass to it “is not a number”.

So, we will use the isNaN() function and pass to it our rotation angle value (as entered by the user). If it’s not a number, we will display our error message.

//check to see if the user's input value is a number or not
if (isNaN(rotation_angle_value)) { //not a number
	$('#error_message').show();
	//rest of code here
}

Step 18: jQuery Updating New Rotation Angle

If the user’s newly entered value is not a number, we’ve displayed an error message. Now we will use an else statement for when they have entered a numeric value. First we hide the error message.

else {
	$('#error_message').hide();
}

Because the rotation angle is stored multiple times in our CSS (due to the various browser prefixes) we have to update ALL of those values with jQuery. So, what we will do is store the syntax of the CSS value in a variable (with the new angle value). Essentially, we are writing rotate(15deg) and replacing the value of ’15′ with the value the user input.

var rotation_angle = 'rotate(' + rotation_angle_value + 'deg)';
similar CSS values

Then we create a CSS object with relational values. We define each of our CSS properties (the browser prefixes for transform), then insert the value as the variable we just defined.

var updated_css = {
	'-webkit-transform' : rotation_angle,
	'-moz-transform' : rotation_angle,
	'-o-transform' : rotation_angle,
	'-ms-transform' : rotation_angle,
	'transform'	: rotation_angle,
}

Now we simply pass that variable storing our CSS properties and values to jQuery to update our CSS!

$('.mask img').css(updated_css);

Step 19: jQuery Final jQuery Code

This is what all our jQuery looks like:

jQuery(document).ready(function($) {
	$('button').click(function() {
		//get the rotation angle value
		var rotation_angle_value = $('#rotation_amount').val();
		if (isNaN(rotation_angle_value)) { //is not a number
			$('#error_message').show();
		}
		else { //is a number
			$('#error_message').hide();
			//store CSS value syntax with the new rotation angle value
			var rotation_angle = 'rotate(' + rotation_angle_value + 'deg)';
			//store CSS properties and values
			var updated_css = {
				'-webkit-transform' :	rotation_angle,
				'-moz-transform'	:	rotation_angle,
				'-o-transform'		:	rotation_angle,
				'-ms-transform'		:	rotation_angle,
				'transform'			:	rotation_angle,
			}
			//update our CSS
			$('.mask img').css(updated_css);
		}
	});
});

Conclusion

I hope you’ve learned something, above all that committing yourself to non-flexible designs in Photoshop is often avoidable by using CSS3 techniques directly in the browser. Thanks for following along!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Pingback: Bilder rotieren mit CSS3 » Webdesign Blog | blog-webdesign.de

  • Pingback: Perfectly Rotate and Mask Thumbnails With CSS3 | Shadowtek | Hosting and Design Solutions

  • http://web.tursos.com Josue Ochoa

    Awesome tutorial, i dont like math but this rocks

  • dj

    Very interesting and useful. Thanks.

  • WallMountedHDD

    Good to know stuff. But three minor things irks me:

    1) Tools needed = code editor. The end. No need to tell us what you use, we all know we just need a text editor at least. I know you Apple people feel the need to use every opportunity to talk about how you use Apple-specific stuff. No one cares.

    2) Change the title to include that it requires jQuery. Titles that say you can do stuff with CSS3 make it sound like you only need CS33. That is misleading.

    3) All the math is cute. And as helpful as it is, let’s be honest. Most people will just slap in values until it looks the way they want. I guess people who kick out html and css all day need to do this kinda stuff to remind themselves they’re not morons. After a while, doing html and css all day is like getting paid to fill in a coloring book. It’s not like doing a HLL with calculus like some coders do all day. Still, it doesn’t look like the script is actually altering the size as you change it on the fly. So if you’re doing all that math just to set it in the first place, trial and error probably would have been quicker.

    • http://www.cirkut.net Josh Allen

      You are both rude and incompetent. While calculus is certainly one of the hardest aspects of mathematics, likening HTML/CSS to filling in a coloring book is extremely rude to every single web designer. Math is most certainly involved in both the design AND development aspects. And it’s not just Apple fans that spout what their favorite text editor is. I hear people all the time who praise Notepad++ (Windows only). We designers and developers just want to recommend to people what we find most useful to us.

      If you actually understand the code, you’d know that the jQuery is an optional step… you don’t NEED to use jQuery for this tutorial.

      And as for the math, it’s not cute, it’s laid out well to explain the logic behind choosing the size of the image thumbnail and the size of the image mask.

      • WallMountedHDD

        Rude? Maybe. Blunt would be more accurate. Incompetent? I don’t think you know the meaning of the word. You’re just upset because I pointed how how elementary this stuff is. That upsets you? Ok, then become a rocket scientist. That’ll shut me up.

        • amidude

          “My God! Why don’t you just tell” him to become “a toll taker at the Golden Gate Bridge! Rocket Scientist, how humiliating!”

        • http://lukewhitehouse.co.uk Luke Whitehouse

          Josh was simply showing you the method behind the madness and how these attributes actually work. Isn’t this the exact definition of a tutorial? (And before you say, no, I do not mean the literal definition from the dictionary).

      • Jesus Bejarano

        I don’t think he was rude , he just expressed himself as natural that his persona can be to give a construtive opinion , if you can’t stand it, please be aware that this kind of things can happend when you post a public service. Btw good tutorial.

  • http://jaymz.eu jaymz

    Excellent article! I really enjoyed this compared to many tutorials you get. +1 for actually including and going into detail on the math.

  • Dusk

    I sort of agree with wallmounted, lots of extra hassle for something that could be achieved by trial and error. Also there is a jquery plugin specific for rotate. Seeing as how most would use the same rotation, that would mean that with a simple plugin and some resizing you have this in probably 5 minutes without having to program it. Google jquery rotate. It works also with gracefull falllback i think.

  • http://www.snaptin.com Ian Yates

    My answer would be: if they don’t interest you, forget the math and forget the additional jQuery bonus. What you’re left with is a really solid idea – using CSS to mask and rotate your thumbnails. Credit where it’s due fellas, come on!

  • http://www.jim-nielsen.com Jim
    Author

    You guys are right. Knowing the math is not essential and neither is the jQuery part (as explained in the tutorial). The basis of the tutorial, as described in the title, is masking images in CSS and using the rotation property in CSS3. I wanted to include the other aspects because I believe they are informative, instructional, and beneficial to understanding how web technologies function. I wanted the tutorial to be practical in real-world application, but I also wanted to try and provide insights into how these trial and error methods of sizing work.

    I myself use trial and error a lot and it’s a great way to learn! In fact, trial and error is often a much quicker method of solving problems than stepping back and coming to an understanding of the problem your solving and the tools you’re using to do it. However, I often yearn to understand the “why” behind my trial and error because detailed explanations are hard to come by. Hence, I wanted to try and provide that kind of supplementary explanation to a practical implementation of CSS.

    WallMountedHDD: For this tutorial, I wanted to devise some kind of function that would allow you to define your mask size and as you change the rotation angle your thumbnail size would automatically be computed. Unfortunately, this type of differntial math is beyond my understanding. If you were able to devise such a function, I would greatly appreciate any explanation of how you did it! I believe it would be a great addition to this tutorial!

    Dusk: Thanks for the tip on jQuery rotate. Knowing how to achieve image rotation via two methods (CSS and now jQuery) means I’ll have just one more tool in the ole’ web development toolbox. Thanks!

  • Pingback: Perfectly Rotate and Mask Thumbnails with CSS3

  • Techeese

    great article about masking and css3.


    @WallMountedHDD: why, so negative the difficulty says beginners to intermediate, just be grateful that you got to read a tutorial about it…

    sure there might be some extra lines of text in the tuts but that doesn’t bother anyone at beginner to intermediate..

  • http://www.villagranstudio.com Leandro

    Great tutorials well explained!
    I agree with Jim in that knowing the “why” of our trial and errors is alwasy better and in my opinion, is what really differentiate real developers from amateurs, for that matter knowledge is alwasy power. right? anyways Thanks for the tutorial keep it up.

  • http://beben-koben.blogspot.com/ Beben Koben

    The creative post…
    The articles look the qualities of a master CSS…hihihi
    from beginning images should be inverted, for so curious…kekekekk
    thanks for tut’s \m/

  • http://technolux.blogspot.com/ TL

    Excellent tutorial! Thanks :)

  • Termin8

    Wow, this is really valuable tutorial! Thanks a lot for taking time to do this huge job Jim! I’m sure that video version of this tutorial would be a must-have thing! Cheers

  • Pingback: Von Fernsehern und neuen Windows 7 Theme Packs - Windows 7, Themes, Windows, Fernseher, Sicherheit, Regen - Die Datenreisenden

  • http://www.lilaostudio.com dlamoureux

    Congrats !

  • Pingback: Perfectly Rotate and Mask Thumbnails With CSS3 | Webdesigntuts+ | Asya Web Design

  • djedie

    Since some browsers still don’t understand CSS3 (what???), do you recommand a specific polyfill js (such as cssSandpaper) who can recreate the rotation effect ?

    Hence, we could use some yepnop + modernizer to make it work in a cross-browser way

  • http://simonwjackson.com Simon W. Jackson

    I wish I would have known about this when I was designing my portfolio…this method is much more scalable.

  • Hitesh Chavda

    Excellent Post,

    I learn some math when i study like Pythagorean theorem. But Now I know where to use these type of maths.

    Thanks..

  • http://danaemc.com Danae

    Very nice read, easy to understand (but I’ll have to go over all the maths again, haha). Inspires me to use css3-transforms and rotation to give it a hover effect of rotation….

  • http://robincrama.nl Robin Crama

    Nice read:)

    Here is a little addition to the css to give the img a cool hoover effect:)

    .mask img:hover {
    -moz-transform: rotate(20deg) scale(.9);
    }

  • hdb

    thanks for the useful and well presented tutorial.

    i would be happy to help with the math, but it seems you have already done the hard part, it just needs to be converted to javascript?

    it may be easier or more elegant to think in terms of the domain of the thumbnail source image thing (the website). basically, rotate the image mask rectangle onto the thumbnail image. this will be the outline of the mask on the thumbnail image. then compute the bounding box of this rectangle, which will give the desired region.

    so for example:
    * my mask is W pixels wide and H pixels in height
    * i want to take a rotated sample from the thumbnail source image (the website) from the position (Xc, Yc). above you take Xc, Yc to be the center of the image.
    * i want the sample to be rotated at an angle of A

    then the rotated sample rectangle – the outline of the mask rectangle in the thumbnail source image – can be computed as follows.

    compute the vertical and horizontal axes of the rectangle after rotation:

    // horiz axis given directly by cos,sin
    Vright = (cos(A) * W/2, sin(A) * H/2)
    // vertical axis is horiz axis rotated by 90 degrees == PI/2 radians
    Vup = (cos(A+PI/2) * W/2, sin(A+PI/2) * H/2)

    Vright, Vup are vectors. in javascript you will just store the x and y values of each vector in separate variables. (e.g. VrightX = cos(A) * W/2, VrightY = sin(A) * H/2).

    you could scale the cos’s and sin’s by some factor to enlarge or reduce the sample region, effectively zooming. (e.g. VrightX = scale*cos(A) * W/2). i think A needs to be radians here – multiply degrees by PI/180 to do the conversion.

    now find the positions of the corners using the rotated axes

    top left corner: (X1,Y1) = (Xc, Yc) – Vright – Vup
    top right corner: (X2,Y1) = (Xc, Yc) + Vright – Vup
    bot left corner : (X1,Y2) = (Xc, Yc) – Vright + Vup
    bot right corner : (X2,Y2) = (Xc, Yc) + Vright + Vup

    if you always want the sample to be taken from the top left corner of the page, use the following:

    top left corner: (X1,Y1) = (0, 0)
    top right corner: (X2,Y1) = 2 * abs(Vright)
    bot left corner : (X1,Y2) = 2 * abs(Vup)
    bot right corner : (X2,Y2) = 2 * abs(Vright) + 2 * abs(Vup)

    where abs take absolute (positive) value.

    finally the required region from the source image – the thumbnail dimensions, step 5 – is the bounding box of the rotated rect:

    thumbnail x1 = min(X1,X2)
    thumbnail y1 = min(Y1,Y2)
    thumbnail x2 = max(X1,X2)
    thumbnail y2 = max(Y1,Y2)

    this should do the trick (might need a debugging iteration to iron out typos and other issues). note i assume that the image y coordinate is top-down, which is why the “top” corners are given by subtracting “Vup” instead of adding. (in any case the sign probably doesnt matter due to the symmetry of the rectangle).

    sorry for the long post but thought it might be useful. hopefully it is understandable.

  • http://hongphuc.info Hongphuc

    OMG! Great, thanks u 4 sharing :)

  • Pingback: Web Development articles, tutorials, help » Blog Archive » Best of Tuts+ in August

  • Pingback: Best of Tuts+ in August | WordPress Themes, Plugins, Hacks, Guides

  • Pingback: Best of Tuts+ in August | Shadowtek | Hosting and Design Solutions

  • Pingback: My Stream » Best of Tuts+ in August

  • Pingback: Best of Tuts+ in August | Webdesigntuts+

  • Pingback: Best of Tuts+ in August | SearchPsd Blog

  • Pingback: Best of Tuts+ in August

  • Pingback: Best of Tuts+ in August | B L O G : : E L I J A H C A R D E R . C O M

  • Pingback: Best of Tuts+ in August | Wptuts+

  • Pingback: Best of Tuts+ in August | Flash Video Traning Source

  • Pingback: Best of Tuts+ in August | Omega Pixels

  • Pingback: Best of Tuts+ in August | Freelancing Help

  • Pingback: Best of Tuts+ in August | Adobe - Обучение

  • Pingback: Finest of Tuts+ in August « Fast Ninja Blog by Freelanceful – Web Design | Coding | Freelancing

  • Pingback: Best of Tuts+ in August – blog

  • Pingback: Ideal of Tuts+ in August « Fast Ninja Blog by Freelanceful – Web Design | Coding | Freelancing

  • Pingback: Best of Tuts+ in August - Tutorial Finder

  • Temitope Akinduro

    Very well explained. Loved the use of math :-p

  • Pingback: Online Articles and Tutorials

  • Mike

    Great program. Anyway to make it work with IE8 though?

  • Pingback: Bilder rotieren mit CSS3 – Link and Friends Blog

  • Pingback: raaaf.de | rafael alex

  • http://www.w3spor.no/webdesign Åsel

    hello, thanks for sharing this great tutorial! Very useful

  • Pingback: How-To Become A specialized Using CSS3 Tutorials | Passcomms Android

  • http://www.atdesigncm.com Thaninrat

    Thankyou. good article for me to learn some css trick.

  • Dan

    Cool Post… Hate Math!.. haha

  • http://blogverize.blogspot.com Nimsrules

    Mathematics + Web Design = ~fTw~

  • juanfevasquez

    Loved the math part actually :) I´m getting a lot into it, want to start developing games with canvas and svg so I enjoy everytime I get the chance to practice basic maths

  • http://www.earn.com.bd md abdul wahed

    its very interesting tutorial. i like it very much.

  • http://edsonjunior.com/ Edson

    I liked this article more about the math than the article itself. The way you get the result is pretty cool but I guess you missed the final touch: The constant (variable) you’ve found first. With only that you could finish all the rest. Let me explain, if the result of the Pythagorean theorem was 300 (the height the image should be), just divide this value by 180 (the height of the mask). As you well said, we are dealing with proportional values. So the constant is 1,67 rounded. But hey, don’t get me wrong, I know your article is for didatic purpose, and I realy enjoyed it! Thanks for share!

  • http://www.vladshap.com Vlad

    Ignore the haters. This is a great tutorial for beginners. As far as the actual effect, its unfortunate that CSS rotation degrades the image slightly and blurs it. While not having to generate hundreds of thumbnails is really nice and efficient, it could be a huge turn off for some people like me due to the blurry/fuzzy outcome of the images.

    Thumbs up.

  • http://jze-studio.com JOSE

    GREAT TUTORIAL! VERY USEFUL.. THANKS :D

  • Fabryz

    The demo doesn’t seem to be working for me: Chrome19/FF12

  • http://www.ravenousravendesign.com Heather Wood

    HOLY MOTHER OF GOD! I saw the Pythagorean Theorem and scrolled, and saw some division and powers of and all that math and I was like. No thanks. I’m done here. I’ll come back and copy and paste this tidbit when I have a few hours of time while I’m drunk :p

  • Hamid

    OMG you kidding me! Brilliant Article, really thx.

  • Pingback: Tweet-Parade (no.24 June 2012) | gonzoblog.nl

  • Pingback: 70 Fresh jQuery and CSS3 Tutorials From 2012

  • Pingback: 50 Useful and Instructive CSS3 Tutorials You Always Wanted To Complete From 2012 | Developer Junk

  • Pingback: 50 Useful and Instructive CSS3 Tutorials You Always Wanted To Complete From 2012 | MNM Tutorials

  • Pingback: 50 Useful and Instructive CSS3 Tutorials You Always Wanted To Complete From 2012 « Resource Sharing ::: . . . . .

  • Pingback: 50 Useful and Instructive CSS3 Tutorials You Always Wanted To Complete From 2012 | Mo Ghaoui, Personal Blog

  • Pingback: 50 Useful and Instructive CSS3 Tutorials You Always Wanted To Complete From 2012

  • Pingback: 30 Must See CSS3 Tips, Tricks And Tutorials : 2012 Edition

  • Pingback: 100 Best CSS3 Tutorials and Tricks for Design Beautiful Websites | SEO Approved

  • Pingback: 50 Useful Fresh CSS3 and jQuery Tutorials | Jisku.com - Developers Network

  • Pingback: 50 Useful Fresh CSS3 and jQuery Tutorials |

  • Pingback: CSS3网页设计实例教程演示及下载 | 港港UED

  • Pingback: 100 MELHORES CSS3 TUTORIAIS E TRUQUES PARA WEBSITES BELO DESIGN | Unconnectable

  • Pingback: Best CSS3 Tutorials of 2012

  • Pingback: 50 Useful Fresh CSS3 and jQuery Tutorials | The Designer Blog

  • Pingback: 20 Latest CSS3 Web Design Tutorials For Pretty Styles | Design Pek

  • Pingback: 100 Best CSS3 Tutorials and Tricks for Design Beautiful Websites | Most Updated : WebHosting,Webmasters,Internet Marketing Tips&Tools ::Web Design Services::

  • Pingback: 50 Useful Fresh CSS3 and jQuery Tutorials | CSS | InstantShift