Use CSS to make the picture adaptive to display width

Source: Internet
Author: User
Tags expression

The company's project needs to display a picture of the user-supplied URI link, but it is not possible to know the size of the picture beforehand, and if the picture size is too large, it will affect the layout of the page. The ideal solution is naturally to generate thumbnails automatically, involving the background work is more complex, with CSS control is an acceptable shortcut.

It seems too smart to force the display size with the Width property. Fortunately, FIREFOX/OPERA/IE7 provides support for max-width properties. Suppose you want the picture to show a width of not more than 500 pixels, CSS may be as follows:

fit-image{ 
   border  :0; 
   max-width:500px; 
}

Let me hate the IE6 does not support the Max-width attribute, but using IE's unique expression attribute can be used to solve the problem in a roundabout way.

fit-image{ 
   border  :0; 
   max-width:500px; 
   width:   expression( 
    function(img){ 
     img.onload=function(){ 
      this.style.width=’’; 
      this.style.width=(this.width>500)?"500px":this.width+"px" 
     }; 
     return’120px’ //加载时显示宽度为120px 
    }(this) 
   ); 
}

Use the OnLoad events to calculate the size of a picture after it has been loaded, or display its default width if it is 500 pixels above 500 pixels.

Expression is not a web-standard practice and should not be used without recommendation. However, we must admit that many of the expansion of IE is good, ie should not be despised!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.