Update:
To support cross-browser, my answer below is to "minimize your" method. However, over the past couple of years, excellent policies have been created to solve this problem. Usually it is a good idea to go with one of them, rather than redo everything that works. Respond.js is one of the most famous. Just a link to it:
<script src="/path/to/respond.js"></script>
Then write the media queries in a css file and you're done.
As Roberk noted, css media queries should be your starting point, but it should be noted that they are not a complete solution to this problem. Unfortunately, css media requests are not supported in all browsers (cough IE). Media request codes in your css files will simply be ignored by these browsers.
In addition to css media requests, I would think of having a backup javascript solution that will determine the size of the viewport and then just add the class to the body tag. This example uses jquery just for brevity:
function setImageClass() { switch(true) { case($(window).width()>600): $("body").removeClass("w200 w400").addClass("w600"); break; case($(window).width()>400): $("body").removeClass("w200 w600").addClass("w400"); break; default: $("body").removeClass("w400 w600").addClass("w200"); break; } } $(document).ready(function() { setImageClass(); }); $(window).resize(function() { setImageClass(); });
Btw, these sizes are not realistic, just for easy testing on all devices. Remember that css media requests will be ignored, so in addition to these, you need to set up rules for classes that set javascript:
.w200 { background:red } .w400 { background:orange } .w600 { background:yellow }
However, you do not want the 2 css rules to collide when both requests and js work, so your media requests should use the same names (and be posted later). For instance:
@media (min-width:200px) { .w200 { background:red; } } ...
I expose the violin to show it in action. This only includes the javascript solution, but again, I fully support media queries as the main solution. Here is the full screen link.