user3622688
user3622688

Reputation: 61

Crop and center image without using background-image

I'm trying to create several images on a page that are the same size, and I'd like to crop and center the source images without resizing them. I've found several answers that do what I need (like here), but they all seem to use background-image. My images, though, are made so that they are black and white and change to color when hovered over, so they are their own class and I can't use the background-image solutions.

Hope that makes sense, it's pretty late. Please let me know if there's any way to do the centering/cropping without background-image, or alternatively have the b/w->color effect on a background-image. Thanks!

Upvotes: 0

Views: 1320

Answers (2)

Hashem Qolami
Hashem Qolami

Reputation: 99484

If using CSS transforms is an option, it can be done even if the dimensions of the images are unknown.

They key point is that a percentage value on translate() notation is relative to the size of bounding box, while a percentage value on top/left properties refers to the size of the box's containing block.

.center-cropped {
  width: 100px;
  height: 100px;
  position: relative;
  overflow: hidden;

  border: 1px solid black;
  margin: 0 auto;
}

.center-cropped img {
  position: absolute;
  top: 50%; left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
<div class="center-cropped">
    <img src="http://placehold.it/200x200" alt="" />
</div>

It's worth noting that CSS transforms are supported in IE9+.

Upvotes: 1

N Kumar
N Kumar

Reputation: 1312

If your image is 200px 200px

div { position:relative; } //parent container
img {
position: absolute;
top: 50%;
left: 50%;
margin-left:-100px;
margin-top:-100px;
}

Upvotes: 0

Related Questions