4

I want to go from this enter image description here

to this

enter image description here

In the first one, the img is responsive widthly. Its width is set to 100%, using bootstrap's .img-responsive.

However, to achieve the desired effect in second pic, we have to leave out part of the images'. To do this, one approach is to set the container of img to a fixed width and height, code goes like this:

<div class="col-md-9">
  <div class="col-md-4 img-container">
    <img src="" class="img-responsive">
  </div>
  <div class="col-md-4"></div>
  <div class="col-md-4"></div>
</div>

(To use folloing approach, delete the `img-responsive' helper above.)

.img-container{
  height: 148px;
  width: 148px;
  img{
    max-height: 100%;
    max-width: 100%;
    vertical-align: middle;
  }
}

However, using Bootstrap's grid to define every <div>'s width.,I don't want to set its witdh and height to a fixed value. That is, I want each <img> or its container to scale according to the col-md-*.

How can I do that, without using fixed width and height? Or put it simply, to set the height according to the width? (or just how to make a square)

ZK Zhao
  • 19,885
  • 47
  • 132
  • 206

1 Answers1

4

I have faced a similar need when building with Bootstrap's grid. I turned to JavaScript (requires jQuery) in order to remedy the situation. Here is my solution: https://gist.github.com/SimpleAnecdote/d74412c7045d247359ed

It's called squareThis() because at first I used it only to make elements square, then I expanded it to mould any element into a rectangle with the help of a ratio. All you need to do is call the function after DOM is ready with any jQuery selector, #ID or .class:

squareThis('.classOfElementsToBeSquared');

The example above will default ot a ratio of 1:1 which will create a square. You may also call the function like this as well:

squareThis('.classOfElementsToBeMoulded', 0.67);

Which will create a 2:3 ratio rectangle (horizontal). You may also:

squareThis('.classOfElementsToBeMoulded', 1, '300');

Which will create squares out of your elements ONLY if the viewport is bigger than 300px.

In your case, I would use Bootstrap's col-md-* classes, add to all the grid elements a class like .square-grid and then:

squareThis('.square-grid');

I hope this function helps you. Please do let me know if you've got any questions about the function, ideas for improvement, etc.

Good luck!

SimpleAnecdote
  • 765
  • 9
  • 17