Enlarge image to match div

I want to scale the image according to the main div class

http://jsfiddle.net/EyW99/

Sorry, forgot to mention that I need it to work in IE8

+6
source share
4 answers

You can use the CSS property background-size:contain .

 .image { background: url('http://astridterese.files.wordpress.com/2010/07/google.jpg') no-repeat; width: 100%; height: 100%; background-size: contain; } 

If you need to support older browsers (namely IE in Windows XP and below, since Vista and 7 users must be in IE9), use the <img> tag instead, since this forces the browser to scale the image to the size you specify either in height / CSS width, or in the attributes of the HTML tag.

<img class="image" src="http://astridterese.files.wordpress.com/2010/07/google.jpg" />

+11
source

Here is the script update version that uses the CSS3 background-size property: http://jsfiddle.net/EyW99/2/

What you need to add to your style, mainly background-size: contain; to scale the image to the maximum possible image size, which is still suitable for your element, or background-size:X% X%; or background-size:Xpx Xpx; if you want to control the size yourself.

Note

As background size is a property of CSS3, it has limited browser support.

IE9 +, Firefox 4+, Opera, Chrome, and Safari 5+.

Translator armor

This solution may not be as good as the new CSS property, but to support cross-browser, you can change the div to img , which allows the browser to resize the image.

+2
source
 .main{ height: 113px; max-width: 400px; } .image { background: url('http://astridterese.files.wordpress.com/2010/07/google.jpg') no-repeat scroll 0 0 transparent; background-size: 100% 100%; } 

This works in Chrome, but not in IE8, so it is probably useless.

Personally, I would change the inner div to an image tag with its width and height set to 100%.

+1
source

If you don't need a clean CSS solution, you can use JavaScript for a solution that works in all major browsers. The bgStretcher plugin for jQuery will do what you want and will dynamically resize if the div is resized.

0
source

Source: https://habr.com/ru/post/911405/


All Articles