Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to give image a dynamic width and height when using bootstrap responsive grid system

I am using bootstrap's grid system and here's my website. The issue is that on initial load the item card looks pretty crappy like this:

enter image description here

and here's what it looks like after it loads:

enter image description here

As you can see the issue is because I am not supplying the image's width and height and hence before it load I am seeing this weird layout which is not good. The issue why I am not supplying a width and height is because this is responsive, such that when I resize the width of the browser then the width of the card also changes, and hence supplying a constant width and height doesn't work. What's the best solution out of this?

like image 568
adit Avatar asked May 21 '14 00:05

adit


People also ask

How can set width and height of image in Bootstrap?

Images in Bootstrap are made responsive with .img-fluid . max-width: 100%; and height: auto; are applied to the image so that it scales with the parent element.

Which Bootstrap class will you use to make Images responsive?

Images in Bootstrap are made responsive with .img-fluid . This applies max-width: 100%; and height: auto; to the image so that it scales with the parent element.

What is XS SM MD lg in Bootstrap?

The Bootstrap 3 grid system has four tiers of classes: xs (phones), sm (tablets), md (desktops), and lg (larger desktops). You can use nearly any combination of these classes to create more dynamic and flexible layouts.


1 Answers

You can calculate your image ratio if it's known then set its padding to the ratio

Check out the js fiddle:

http://jsfiddle.net/J8AYY/7/

<div class="img-container">
    <img src="">
</div>

.img-container {
    position:relative;
    padding-top:66.59%;
}

img {
    position: absolute;
    top: 0;
    left: 0;
    width:100%;
}

So if your image has width 2197 pixels and height 1463 pixels

then set the container that contain the image to have padding-top 1463/2197*100% then set your image to position absolute now your image can be responsive and worry free of collapsing container

like image 117
Chihung Yu Avatar answered Sep 20 '22 14:09

Chihung Yu