0
votes

So i have a div that is 100px wide/high, in it i want to show an image (lets say the image is 200px in width/height).
The image should not be resized, the div should only show the center of the image (100px of it) and hide the rest.

You can better see what i mean in the image below:
http://i.imgur.com/b8nbnO1.png

<div class="crop-image">
<a href="some link"><img src="http://i.imgur.com/b8nbnO1.png" /></a>
</div>

And if the image is smaller than 100px apply a padding to the link of
(100px - image width)/2 for padding left and right
(100px - image height)/2 for padding top and bottom

2
Use a background image instead. - Paulie_D
I would suggest doing it via background image, that you could center and offset, or you could use negative margins on the image element to set what's visible in the area. - Isti115
The image should be a link i'm sorry i forgot to add it first. I have edited the question. - fbg13
@CK13 with my solution you may still use a link around the image - Fabrizio Calderan
Thanks everyone for the help. - fbg13

2 Answers

2
votes

You can do this by using background-image and background-position like so:

div {
    width:100px;
    height:100px;
    background-image:url('http://www.placehold.it/200/200/');
    background-position:center;
}

Here is a fiddle showing it off: http://jsfiddle.net/A4wQE/

By setting the height and width of the div element you can "crop" an image that is larger. Also, use background-position:center; to make sure it is always centered in the div.

UPDATE

Since you need the image to be a link you can simply wrap the div in an a tag. As of HTML5, <a> elements are allowed to contain block elements.

1
votes

If your image conveys content it should not be placed as a background: so you could use the object-fit property.

By default the image will be in center position, but you can change it via object-position

.crop-image {
   height: 100px;
   width : 100px;
}


.crop-image img {
   max-width: 100%;
   object-fit: none;
}
<div class="crop-image">
   <a href="#">
     <img src="http://dummyimage.com/200x200/000/fff" />
   </a>
</div>