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
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.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.