Grow your CSS skills. Land your dream job.

Last updated on:

Fix Min/Max-Width for Browsers Without Native Support

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>

Reference URL

Comments

  1. justin

    hmm…when i try to implement this, ie6 is unable to parse the maxWidth and minWidth values. modern browsers can interpret them correctly. have you been able to use this successfully?

  2. justin

    i figured it out. i’m using a global style of max-width: 100% on all images. since ie6 calculates that percentage relative to the image size rather than the parent element the effect was failing. i set maxWidth to the width of each image’s parent instead of the explicit 100% from the css and that seems to do the trick. not quite sure what to do for min-width. alternatively, a set of ie6 specific css targeting all possible max-widths would work with the existing code but would quickly get unwieldy.

  3. John
    Permalink to comment#

    I think this is a more elegant solution for the same idea, and it works back including IE6. It’s designed for fullscreen flash with minimums, but the concept could apply without flash as well. (though it’s not designed for maximums, just min)

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".