As pointed out elsewere, you could use max-height
and max-width
, which is good. But I'd like to take it a step further, and make it so that it doesn't matter what the container size is.
Use a percentage value instead of 200px
:
img {
max-width: 100%;
max-height: 100%;
}
Here is an example:
.container {
border: 5px solid blue;
width: 200px;
height: 200px;
}
img {
max-width: 100%;
max-height: 100%;
}
<div class="container">
<img src="http://www.piprd.com/images/400X200.gif">
</div>
<div class="container">
<img src="https://fakeimg.pl/200x400/">
</div>
To prove this works, I have written some code (unnecessary for your actual code). You just need to enter the desired width + height for the container, and you can see the effect!
function size() {
var width = prompt("Please enter width for container", "200px");
var height = prompt("Please enter height for container", "200px");
if (width != null) {
$('.container').css('width', width);
}
if (height != null) {
$('.container').css('height', height);
}
}
.container {
border: 5px solid blue;
width: 200px;
height: 200px;
}
img {
max-width: 100%;
max-height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button style="float: right;" onclick="size()">Choose size values</button>
<div class="container">
<img src="http://www.piprd.com/images/400X200.gif">
</div>
<div class="container">
<img src="https://fakeimg.pl/200x400/">
</div>