How to place the whole image in divs that have its dimensions
<div class = "container"> <div class = "row"> <small>Original picture size is 876x493, I resize it to:</small> <div class = "property"> <img src = "http://a57.foxnews.com/global.fncstatic.com/static/managed/img/Leisure/2009/876/493/big-house-small-house.png?ve=1&tl=1"/> </div> <small>Result I want to get (in another way):</small> <div class = "property"> <img style = "max-width: 147%" src = "http://a57.foxnews.com/global.fncstatic.com/static/managed/img/Leisure/2009/876/493/big-house-small-house.png?ve=1&tl=1"/> </div> </div> </div> https://jsfiddle.net/40ay7uco/
I want to reduce my image so that it matches it in the div. How can I do this using jquery or css, without mannualy, as I did before.
ps I want to keep the width factor: height
+5
5 answers
You can set background-image using jQuery and use background-size: cover; on property div
$('.property').each(function() { var background = $(this).data('background'); $(this).css('background-image', 'url('+background+')'); }); .property { border: 3px solid white; box-shadow: 0px 0px 5px #aaaaaa; width: 270px; height: 200px; overflow: hidden; background-size: cover; background-position: center; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class = "container"> <div class = "row"> <small>Original picture size is 876x493, I resize it to:</small> <div class = "property" data-background="http://a57.foxnews.com/global.fncstatic.com/static/managed/img/Leisure/2009/876/493/big-house-small-house.png?ve=1&tl=1"> </div> <div class = "property" data-background="http://placehold.it/350x150"> </div> <div class = "property" data-background="http://placehold.it/700x500/ffffff/000000"> </div> </div> +1
You set the maximum sizes for your image, so it only appeared at its own resolution. If you set the width to auto size, this will maintain the ratio.
This should work:
.property { border: 3px solid white; box-shadow: 0px 0px 5px #aaaaaa; width: 270px; height: 200px; /*This will keep aspect ratio for your image*/ overflow: hidden; } .property img { height: 100%; /*This will keep aspect ratio for your image*/ width: auto; /*Not necessary since this is the default value*/ } <div class = "container"> <div class = "row"> <div class = "property"> <img src = "http://a57.foxnews.com/global.fncstatic.com/static/managed/img/Leisure/2009/876/493/big-house-small-house.png?ve=1&tl=1"/> </div> </div> </div> As you can see, the image goes beyond the div, even if it is not visible.
+2
If you want to keep the size, the image width should be automatic.
.property { border: 3px solid white; box-shadow: 0px 0px 5px #aaaaaa; width: 270px; height: 200px; overflow: hidden; } .property img { max-width: 100%; /*Should remove*/ max-height: 100%; /*Should remove*/ width: auto; height: 100%; } I edited your code. You can check https://jsfiddle.net/dtv6bk75/
+1
