JoaMika
JoaMika

Reputation: 1827

Responsive Image with Max-height & Max-width

I have this html and CSS

<div class="kalim"><img  src=""></div>

CSS

.kalim {display: inline-block;}

.kalim img {max-width: 800px;width: auto;max-height: 800px;}

The problem with this code is that the images are not responsive in width when the browser is resized. If I set width:100% then the portrait images exceeding 800px in height become distorted.

Is there a workaround for this, to make the image responsive and also have the max-height and max-width settings?

Upvotes: 9

Views: 22046

Answers (4)

Danny
Danny

Reputation: 71

We can use object-fit to make the answer simpler:

.kalim img {max-width: 800px; max-height: 800px; object-fit: contain;}

or

.kalim img {max-width: 800px; max-height: 800px; object-fit: cover;}

Reference: https://www.w3schools.com/css/css3_object-fit.asp

Upvotes: 6

Kolappan N
Kolappan N

Reputation: 4011

In Bootstrap 4, you can add the class img-fluid and set width and height properties.

<img class="img-fluid" src="https://source.unsplash.com/random/1600x1600" width="800" height="800">

As you can the the size of the image is 1600x1600 but it will not exceed the size of 800x800 in the webpage. Also this is responsive.

<html>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<img class="img-fluid" src="https://source.unsplash.com/random/1600x1600" width="800" height="800" alt="Image from unsplash">

</html>

Upvotes: 0

Leroy
Leroy

Reputation: 2137

You should add the width restriction to the outer element instead of the image. The outer element will not size over your max-width and max-height, but the image will always be 100% in width. This way your image will be responsive.

html

 <div class="kalim"><img src=""></div>

css

.kalim {display: inline-block; max-width: 800px; max-height: 800px;}

.kalim img {max-width: 100%; height:auto;}

Upvotes: 17

Joel Garcia Nu&#241;o
Joel Garcia Nu&#241;o

Reputation: 933

Like the bootstrap class css of img-responsive or img-fluid bs4

<img src="chicago.jpg" style="max-width: 100%; height: auto; width: 800px"/>

Upvotes: 1

Related Questions