1
votes

I'm creating a responsive gallery and my client sends me image that are landscape and portrait and varies sizes.

I'm trying to create a way to take an inline image and keep the aspect ratio the same by using css.

Here is a link to the code pen I created. Please feel free to edit.

http://codepen.io/daugaard47/pen/mpado

The image inside the box is 3137 x 4012 What I'm trying to do is keep the image width at 100% inside the grid_3 by using the class max-img-border.

Then I want the height to keep the same aspect ratio, so the image isn't squished, but hidden. So for example the top of the tree would be hidden by the overflow:hidden command in the class max-img-border.

How would I achieve this?

Also if you can achieve this, is there a way to add position:center center?

Here is the code if you dont want to look at the code pen.

HTML

<body>

<div class="tree">

  <div class="grid_3">
    <a class="fancybox" rel="gallery1" href="http://upload.wikimedia.org/wikipedia/commons/f/fe/Tree_at_Golf_Course.JPG" title="Tree removal">
      <img src="http://upload.wikimedia.org/wikipedia/commons/f/fe/Tree_at_Golf_Course.JPG" alt="Tree removal" class="max-img-border">
    </a>
    <h5>Tree Removal</h5>
  </div>

</div>

</body>

And here is the css

CSS

body{
    background-color:#1f1f1f;
}

.tree{
    margin:150px auto;
}

.grid_3 {
    width:260px;
    margin:0 20px;
    float:left;
    display:inline;
}

.max-img-border {
    width:100%;
    height:auto;
    max-height:180px;
    border:solid 2px #FFFFFF;
    margin-bottom:10px;
    overflow:hidden;
    display:inline-block; 
}

h5 {
    margin:0 0 10px 0;
    padding:0;
    font-size:17px;
    line-height:19px;
    color:#FFFFFF;
    font-weight:700;
    text-shadow: 0 2px 2px rgba(0, 0, 0, 0.75);
    text-align:center;
}
1
you don't set any height to your box, how do you expect to hide somthing , except for the width ? - G-Cyrillus

1 Answers

1
votes

you could use vertical-align and negative margin to virtually reduce height of image.

http://codepen.io/gcyrillus/pen/Grbxg

.grid_3 {
    width:260px;
    margin:0 20px;
    float:left;
    text-align:center;
    overflow:hidden;
    background:rgba(255,255,255,0.02);
}

.grid_3 a {
  display:block;  
  height:171px; border:solid 2px #FFFFFF;
  line-height:168px;
  overflow:hidden;
  margin-bottom:10px;
}

.max-img-border {
    width:100%;
    margin:-100% 0;
    vertical-align:middle;
}