Sometimes we need to display the image in a fixed area. If you do not consider IE6, you can use the max-width limit of css to automatically scale down the display according to the proportion. However, the problem is that the image height is insufficient after the scale-down, that's ugly.
For example
First case: the slice size is 600 × 350, and the display area size is 200 × 140. If the image is scaled proportionally to 200 based on the target width (116, it will be ugly if it is displayed at 200 × 140. For example, left
Case 2: on the contrary, the slice size is 400 × 400, and the display area is also 200 × 140. If the image is scaled proportionally to the target height (140), the size will change to 140, that is, 140 × 140, which is also ugly. For example, right
In this case, it is slightly better to use jQuery to get the image size and then judge and process it. For example, in the first case, calculate the width of 140x140 = 600/350 Based on the height of 240, and then display the image as 240x140, the extra part is hidden with overflow: Den den of css.
The following is my solution: (Note-if the width and height of the original image are greater than the size of the target display box, which is called narrowing down)
Demo here
Html section
If the class in the display area is thumbnail
The Code is as follows:
Css Section
The Code is as follows:
. Thumbnail {overflow: hidden; width: 200px; height: 140px ;}
JQuery Section
1. Of course, the jQuery library is suspended first.
2. Core code
JQuery (document ). ready (function () {/* automatically scales out incomplete images by zwwooooo */$ (window ). load (function () {$ ('# content p. thumbnail img '). each (function () {var x = 200; // fill in the target image width var y = 140; // fill in the Target Image Height var w = $ (this ). width (), h = $ (this ). height (); // obtain the image width and height if (w> x) {// when the image width is greater than the target width, var w_original = w, h_original = h; h = h * (x/w); // calculate the height w = x based on the target width in proportion; // The width is equal to the predefined WIDTH if (h <y) {// If the scaled down height is smaller than the predefined height, w = w_original * (y/h_original); // calculate the width h = y based on the target height; // The height is equal to the predetermined height }}$ (this ). attr ({width: w, height: h });});});});
Applicable places: fixed-size image display areas, such as thumbnails.
After all.
The following is a common image size control code on the recommended content page: