Fix Min/Max-Width for Browsers Without Native Support

Avatar of Chris Coyier
Chris Coyier on

This script checks all elements with a class of .fixMinMaxwidth and observes the window. It’s only applied to browsers without native min/max-width support such as ie6 and below. Window resizing won’t be a problem either.

<script type="text/javascript">
//anonymous function to check all elements with class .fixMinMaxwidth
var fixMinMaxwidth=function()
{
       //only apply this fix to browsers without native support
       if (typeof document.body.style.maxHeight !== "undefined" &&
               typeof document.body.style.minHeight !== "undefined") return false;

       //loop through all elements
       $('.fixMinMaxwidth').each(function()
       {
               //get max and minwidth via jquery
               var maxWidth = parseInt($(this).css("max-width"));
               var minWidth = parseInt($(this).css("min-width"));

               //if min-/maxwidth is set, apply the script
               if (maxWidth>0 && $(this).width()>maxWidth) {
                       $(this).width(maxWidth);
               } else if (minWidth>0 && $(this).width()<minWidth) {
                       $(this).width(minWidth);
               }
       });
}

//initialize on domready
$(document).ready(function()
{
       fixMinMaxwidth();
});

//check after every resize
$(window).bind("resize", function()
{
       fixMinMaxwidth();
});
</script>