September 14, 2014

How to crop an image to fit inside a container using css?

How to crop an image to fit inside a container using css

I thought this idea when i where creating a thumbnail gallery.

An old method to do this is by editing the thumbnail to the required size using any photo editor. Here there will be two images used. One a thumbnail of a required size, where you have to make all thumbnail sizes look alike. Second a larger image. When the thumbnail image is clicked the larger image is viewed. So, here two images of different sizes are required.

Another easy method, where you can crop the larger image to fit it as a thumbnail in a container. You may have different image sizes, where you have to crop it and make it fit into a container. For this if you change the size of images you wont get the equal proportion as the image size may vary. To attain this, you can crop an image to the required size of the container and fix into it. So that all the images size are proportionate.

I did this by using overflow: hidden

HTML

<div>
  <div class="container"> 
    <img src="http://1.bp.blogspot.com/-B0NJPAjVWO0/U_DHwvo8OhI/AAAAAAAAHBk/RtyWNlT9j_0/s1600/sample.jpg" />
  </div>
  <div class="container"> 
    <img src="http://1.bp.blogspot.com/-B0NJPAjVWO0/U_DHwvo8OhI/AAAAAAAAHBk/RtyWNlT9j_0/s1600/sample.jpg" />
  </div>
  <div class="container"> 
    <img src="http://1.bp.blogspot.com/-B0NJPAjVWO0/U_DHwvo8OhI/AAAAAAAAHBk/RtyWNlT9j_0/s1600/sample.jpg" />
  </div>
</div>

CSS

.container {
  width: 250px;
  height: 250px;
  border: 3px solid black;
  border-radius: 5px;
  overflow: hidden;
  float: left;
  margin: 0 10px;
}

Note:

In the demo example the image size is 1140 X 580. The container size is 250 X 250. I need the crop the image to fix the thumbnail container

demo

No comments:

Post a Comment

Popular Posts

Views