user3681788
user3681788

Reputation: 221

CSS "crop" images, but align in center vertically

I'm currently cropping images with CSS as so:

<div class="crop">
    <img src="image.png" alt="">
</div>

.crop {
width: 150px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 150px;
height: auto;
margin: 0 0 0 0;
}

This way, it aligns the image within the container horizontally. However, I have no idea how to align the image vertically in the center (so it's right in the middle). Any help?

Upvotes: 4

Views: 7816

Answers (4)

smarteist
smarteist

Reputation: 1421

Use these classes :


.center-crop-img {
  object-fit: none; /* Do not scale the image */
  object-position: center; /* Center the image within the element */
  width: 100%;
}

.center-crop-img-cover {
  object-fit: cover; /* cover image */
  object-position: center; /* Center the image within the element */
  width: 100%;
}

.center-crop-img-contain {
  object-fit: contain; /* contain the image */
  object-position: center; /* Center the image within the element */
  width: 100%;
}

.center-crop-img-scale-down {
  object-fit: scale-down; /* scale-down the image */
  object-position: center; /* Center the image within the element */
  width: 100%;
}

Upvotes: 1

Nikolay Sergeevich
Nikolay Sergeevich

Reputation: 106

/* Just gonna leave this here.. */

.crop {
    position: relative;
    overflow: hidden;
    height: 180px;
    margin: 8px;
}
.crop img {
    position: absolute;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

Upvotes: 8

Anshuman Singh
Anshuman Singh

Reputation: 1152

use

 .crop img{top:50%; left:50%;}

OR USE-

 .crop img{vertical-align:middle;}

Upvotes: -1

Aravind
Aravind

Reputation: 609

As suggested by @RanSch, you can crop the image using clip attribute.

.imgClass{
   clip:rect(top,right,bottom,0px);
   margin-top: //someValue or
   vertical-align: middle; //or
   top: //someValue or
}

Upvotes: 0

Related Questions