Mo Mononoke Mo Mononoke - 21 days ago 7
CSS Question

Make 1:1 scaled image out of tall image without making it wide

I was wondering if I could show width-matched part of an image within a div? I've tried using things like

width:100%;
, but that still shows the full tall image only way too wide. I'm using a 4-column Bootstrap template to try and print images. Here's my code (with another style code that didn't work out..):

echo "<div class='col-md-3 portfolio-item'>";
echo "<a href='#'>";
$url = $row['url'];
echo "<img style='object-fit:contain;max-height:240px;' class='img-responsive' src='".$url."' alt=''>";
echo "</a>";
echo "</div>";


Example of a tall image: http://i.imgur.com/ux6PckG.jpg

How I want it to be displayed (top, bottom or middle doesn't matter): http://i.imgur.com/Rt5yAOb.png

How it is currently displayed (white square to the right of it): http://i.imgur.com/H7iGcj4.png

If I set the
max-width
and
max-height
of the image anchor, can I display only part of it (top, bottom or middle doesn't matter) without having to crop a thumbnail myself?

Having a massively hard time explaining my problem, sorry about that. I'm not sure where to start, my Googling hasn't led me anywhere, probably not using the correct terms.

Answer

The problem is that your .portfolio-item is resized due to the image. You have to force a box of 1:1 ratio that will restrict the image (with overflow:hidden)

.portfolio-item.square{position:relative}
.portfolio-item.square:before{
  content:'';
  display:block;
  padding-top:100%;
}
.portfolio-item.square > a{
  display:block;
  position:absolute;
  top:0;left:0;
  width:100%;
  height:100%;
  overflow:hidden;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
  <div class="row">
    <div class='col-md-3 portfolio-item square'>
      <a href='#'>
        <img style='max-width:100%;' class='img-responsive' src='http://i.imgur.com/ux6PckG.jpg' alt=''>"
      </a>
    </div>
    <div class='col-md-3 portfolio-item square'>
      <a href='#'>
        <img style='max-width:100%;' class='img-responsive' src='http://i.imgur.com/ux6PckG.jpg' alt=''>"
      </a>
    </div>
    <div class='col-md-3 portfolio-item square'>
      <a href='#'>
        <img style='max-width:100%;' class='img-responsive' src='http://i.imgur.com/ux6PckG.jpg' alt=''>"
      </a>
    </div>
    <div class='col-md-3 portfolio-item square'>
      <a href='#'>
        <img style='max-width:100%;' class='img-responsive' src='http://i.imgur.com/ux6PckG.jpg' alt=''>"
      </a>
    </div>
  </div>
</div>


Even better would be to set the image as a background to the a tag, this way you will have control over how to align the image (top/bottom/right...) through background-position:...