20

I am using a div tag in code as shown below:

<div class="col-sm-6 col-md-6 col-lg-4">
  <img src="images/dummy_image.png" class="img-responsive">
</div>

The user can upload any kind of image and have it displayed here. I want to fit the image inside of the div, meaning specifically that I need to cover the full div using that image as it's resized.

I am using Bootstrap 3.3.7. Please advise.

ruffin
  • 16,507
  • 9
  • 88
  • 138
user1770268
  • 311
  • 1
  • 2
  • 4

3 Answers3

37

Just add you images width to 100%.

But as you are saying user will upload various kind of images, so can use object-fit property.

Add the CSS like this:

.fit-image{
width: 100%;
object-fit: cover;
height: 300px; /* only if you want fixed height */
}

<div class="col-sm-6 col-md-6 col-lg-4">
<img src="images/dummy_image.png" class="img-responsive fit-image">
</div>

You will find the details about object-fit and object-position here : https://css-tricks.com/on-object-fit-and-object-position/

Zahidul Islam Ruhel
  • 1,114
  • 7
  • 17
19

For Bootstrap 4

<div class="col-sm-6 col-md-6 col-lg-4">
    <img src="images/dummy_image.png" class="img-fluid">
</div>

bootstrap.css

.img-fluid {
  max-width: 100%;
  height: auto
}
JohnB
  • 18,046
  • 16
  • 98
  • 110
Dawit Abraham
  • 1,616
  • 15
  • 19
2

It is safe to assume that by fitting you mean covering all of the width. This is because

  1. You typically do not know the height just by using col-sm-6 or col-md-6 or col-lg-4.
  2. There is a huge probability of loss in aspect ratio of the image if you try to resize it according to your own will.

Use <img src = "images/dummy_image.png" class = "img-responsive" width = "100%" /> for fitting the column. This will fit your image width-wise into the column and will automatically modify the height (keeping the aspect ratio in mind), so you do not have to worry about image getting illogically resized.

Pranav Totla
  • 2,182
  • 2
  • 20
  • 28
  • Not wrong. But if you're using bootstrap, you can avoid using width="100%" with the bootstrap class "w-100". It's a bit cleaner. – RockyK Apr 03 '20 at 17:55